Two List Difference
I have two similar lists and want to create a new list with just the differences between the two. Is there an existing function or do I have to iterate with a for loop?
Ene Uran
Posting Virtuoso
1,723 posts since Aug 2005
Reputation Points: 625
Solved Threads: 213
You have to select one of the lists as reference, if they are not of the same length, use the longer list. Here is an example using the standard for loop and the simpler list comprehension ...
# check two lists for the difference
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = [1, 2, 3, 4, 4, 6, 7, 8, 11, 77]
def list_difference(list1, list2):
"""uses list1 as the reference, returns list of items not in list2"""
diff_list = []
for item in list1:
if not item in list2:
diff_list.append(item)
return diff_list
print list_difference(list1, list2) # [5, 9, 10]
# simpler using list comprehension
diff_list = [item for item in list1 if not item in list2]
print diff_list # [5, 9, 10]
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
Hi,
List1=[5,8,9,11]
List2=[8,9]
List3=list(set(List1-List2))
print List3 #[5,11]
useList3=list(set(List1)-set(List2))
and it will work
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
Actually, Python3 has modernized the set() function.
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
Any ideas when python 3 will be the norm? it doesn't appear ANYONE is racing forward... have to wonder how extensive the bugs are in the new version...
On the contrary, everybody is racing forward. The problem is that we all use third party python modules which are not yet compatible with python 3. I think that a good alternative is to install both python 2.6 and python 3.last on your machine and try to write code which runs under both pythons. This way, you learn python 3 and at the same time, you write code usable by everybody.
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691