NEWBIE QUESTIION: Comparing Lists in Python
Mark McEahern
marklists at mceahern.com
Wed May 1 22:23:23 EDT 2002
[Dianne van Dulken]
> I want to return the difference between the two lists as again two lists
>
> eg:
>
> list 1 = item1, item5, item8, item10
> list2 = item 3, item4, item5
>
> I want to return
>
> returnlist1 = item1, item8, item10
> returnlist2 = item3, item4
You can do this easily with list comprehension. Here's a demo...
#!/usr/bin/env python
def not_in_list(l1, l2):
"""
Return a list of elements from l1 that are not in l2.
"""
return [x for x in l1 if x not in l2]
l1 = [1,5,8,10]
l2 = [3,4,5]
print not_in_list(l1, l2)
print not_in_list(l2, l1)
// mark
More information about the Python-list
mailing list