By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,035 Members | 1,384 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,035 IT Pros & Developers. It's quick & easy.

Getting the difference between two lists

100+
P: 440
Hi,

I have two lists,i have to get the remaining list elements other than common elements.

I/P :

l1 = [1,2,3,4]
l2=[2,3]

O/P
From l1 & l2.I have to get the uncommon elements
[1,4]

Thanks
PSB
May 20 '07 #1
Share this Question
Share on Google+
3 Replies


bartonc
Expert 5K+
P: 6,596
Hi,

I have two lists,i have to get the remaining list elements other than common elements.

I/P :

l1 = [1,2,3,4]
l2=[2,3]

O/P
From l1 & l2.I have to get the uncommon elements
[1,4]

Thanks
PSB
With sets you can do union, intersection, ect. Or:
>>> l1 = [1, 2, 3, 4]
>>> l2 = [2, 3]
>>> list(set(l1) - set(l2))
[1, 4]
>>>
May 20 '07 #2

Expert 100+
P: 511
you should be able to understand how to use sets by now, since barton has showed you how here
May 20 '07 #3

bvdet
Expert Mod 2.5K+
P: 2,851
If you do not want to use sets, you could do this:
Expand|Select|Wrap|Line Numbers
  1. >>> lst1 = [1,2,3,4,5,6,7,8,9,0,11,12,13]
  2. >>> lst2 = [5,6,7,12,45,67,89,99]
  3. >>> [i for i in lst1+lst2 if i not in lst1 or i not in lst2]
  4. [1, 2, 3, 4, 8, 9, 0, 11, 13, 45, 67, 89, 99]
  5. >>> 
May 20 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.