[Tutor] newB Q: extracting common elements from 2 lists

Sean 'Shaleh' Perry shalehperry@attbi.com
Mon, 24 Jun 2002 09:53:13 -0700 (PDT)


> 
> I have two tuples where the values are lists,
> eg :
>>>> xmap
> {1: [1, 3, 5, 7, 9]}
>>>> ymap
> {1: [1, 2, 3, 4, 5]}
> 

you have a dictionary, not a tuple.  A tuple is like a list but it is constant.

tup = (1,3,5,7,9) # make a tuple

> what I want is to extract the common elements of the
> two tuple values and put them in a new tuple 'list'
> 
> like:
> 
> xymap[1] = xmap[1] *something magic here* ymap[1]
> 
> so xymap[1] contains [1,3,5].
> 
> can it be done?  - as tuples or converted to lists and
> done somehow?
> 
> I found that xymap[1] = xmap[1] and ymap[1] just
> combined the list rather than binary anding them (and
> & caused an error).
> 
> Any advice gratefully received.
> 

def common_elements(list1, list2):
    common = []
    for item in list1:
        if item in list2:
            common.append(item)

xymap[1] = common_elements(xmap[1], ymap[1])

note for large lists this will be a little slow, but it should not be too bad.