tags:

views:

92

answers:

2

We have two lists:

a=['1','2','3','4']
b=['2','3','4','5']

How to get a list with elements that are contained in both lists:

a_and_b=['2','3','4']

and a list with elements that are contained only in one list, but not the other:

only_a=['1']
only_b=['5']

Yes, I can use cycles, but it's lame =)

+8  A: 

if order is not important

>>> a=['1','2','3','4']
>>> b=['2','3','4','5']
>>> set(a) & set(b)
set(['3', '2', '4'])

only a

>>> set(a).difference(b) # or set(a) - set(b)
set(['1'])

only b

>>> set(b).difference(a)  # or set(b) - set(a)
set(['5'])
ghostdog74
you don't need to cast to set `.difference` argument.
SilentGhost
yes, we don't need to, but some one may like to look at words. :)
ghostdog74
What SilentGhost means is you can do `set(a).difference(b)`
orip
+6  A: 

Simply with the use of sets:

>>> a=['1','2','3','4']; b=['2','3','4','5']
>>> a = set(a)
>>> b = set(b)
>>> a & b
set(['3', '2', '4'])
>>> a - b
set(['1'])
>>> b - a
set(['5'])
>>>
MattH