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

alan.gauld@bt.com alan.gauld@bt.com
Mon, 24 Jun 2002 18:04:12 +0100


> I've just discovered the tutor list, I'm hoping to
> learn a lot more about Python by reading other peoples
> querys/answers.

Welcome :-)

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

To be pedantic that's a dictionary not a tuple.
But it doesn't make much difference to your question...

> what I want is to extract the common elements of the
> two tuple values and put them in a new tuple 'list'

You know how to get the lists out of the dictionary 
so lets ignore that part and talk about two lists 
L1 and L2.

Theres some clever code shortening can be done here 
but lets keep it simple first off. 

L3 = []
for item in L1:
   if item in L2:
      L3.append(item)

Using list comprehensions we can do it in oner line:

L3 = [item for item in L1 if item in L2]

HTH,

Alan G.