faqts : Computers : Programming : Languages : Python : Common Problems : Lists

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

31 of 36 people (86%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

Is there a function returning the intersection of two lists?

Oct 17th, 2004 14:27
Josh Lee, unknown unknown, Penfold


Example:

l1 = [1,2,3,4,5]
l2 = [4,5,6,7,8]

l3 should be [4,5]

Solution:

You could try using the ever useful kjbuckets module (find it on
http://www.vex.net/parnassus).

This implements mathematical sets and graphs which mean your below 
becomes as easy as

kjSet([1,2,3,4,5]) & kjSet([4,5,6,7,8])

Solution:
Or, without the added complexity of sets, just type:
l3 = [n for n in l1 if n in l2]