What is the best way to merge two lists?

Pierre Rouleau pieroul at attglobal.net
Sun Nov 17 14:45:24 EST 2002


> Your question really boils down to getting unique items from a list,
> stably.  You can always just concatenate your two lists and then
> unique them, so the merge question is secondary.
Yep, good way to describe it :)

> 
> Take a look at Tim Peter's recipe at
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560.
> 
> His approach is to try alternate methods in order of decreasing
> efficiency, moving to the next if the previous fails.  I think his
> sort based approach for non-hashable elements will offer improved
> performance over your brute force approach.
Thanks! I like the approach of trying efficient algorithm first and 
making the code work its way down in efficiency while ensuring the 
function always works.  I am always amazed at how easy thing are in Python!

> 
> However, the builtin sort is not stable,
In what sense?


> so I don't think it will meet
> your criterion of deterministic output. But there is a fair amount of
> discussion on that page about the best way to get uniqueness in the
> presence of possibly unhashable elements, and various approaches for
> dealing with stability -- see Alex's comments after the recipe.
> 
The other thing about Python: what a nice community to know!


Thanks again,

Pierre




More information about the Python-list mailing list