[Tutor] Lists...

D-Man dsh8290@rit.edu
Wed, 30 May 2001 22:52:03 -0400


On Thu, May 31, 2001 at 10:36:10AM +0800, Andrew Wilkins wrote:
| Hi people,
| 
| Is there a way of returning the intersection of two lists?
| Eg. [1,2,'3',4.0,'x'] & [1,8,'3',9,10,'x'] to return [1,'3','x']

(untested)

def instersect( l1 , l2 ) :
    result = []
    for item in l1 :
        if item in l2 :
            result.append( item )

    return result

If the lists get large, this will have horrible performance because
the "item in l2" performs a linear search.  If you can create a
dictionary from one of the lists then the speed of the inersection
will be improved, but time will be spent building the citionary.  (It
is faster because the has_key method hashes the key and checks if it
exists rather than performing a linear search on a list)

This list comprehension shoud do the same thing :

def intersect( l1 , l2 ) :
    return [ item for item in l1 if item in l2 ]


-D