What is the best way to merge two lists?

John Hunter jdhunter at nitace.bsd.uchicago.edu
Sat Nov 16 23:16:59 EST 2002


>>>>> "Pierre" == Pierre Rouleau <pieroul at attglobal.net> writes:

    Pierre> What's the most efficient way to merge two lists inside a
    Pierre> single one with the resulting list having only one
    Pierre> instance of each element (ie not having two elements with
    Pierre> the same value)?

    Pierre> The order of the elements is not a criteria for the
    Pierre> selection of the algorithm.

The best way will depend on the size of the list and the type of
elements contained in each, but for Merge Lists 101, the best approach
is to use a dictionary.

If you can afford the memory consumption, the following will give
pretty good performance

l1 = [1,2,3,4]
l2 = [2,3,12,14]

m = dict( [(x,1) for x in l1+l2])
print m.keys()

If memory is an issue, you can process each list separately:

m1 = dict( [(x,1) for x in l1])
m1.update( dict( [(x,1) for x in l2]))
print m1.keys()


The solutions above require a recent version of python (2.2+).  For
older versions (<2.0), use the manual loop, which is slower but will
run on pretty much any python

m = {}
for x in l1+l2: 
    m[x]=1
print m.keys()

If performance is critical and the lists contain numeric values, take
a look at the Numeric module.

John Hunter




More information about the Python-list mailing list