Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a list with elements that are contained in two other lists?

Tags:

python

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 =)

like image 672
user285070 Avatar asked Dec 03 '25 11:12

user285070


2 Answers

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'])
like image 107
ghostdog74 Avatar answered Dec 04 '25 23:12

ghostdog74


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'])
>>>
like image 24
MattH Avatar answered Dec 04 '25 23:12

MattH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!