How to get a list with items contained in two other lists?

We have two lists:

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

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

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

and a list with items contained in only one list, but not the other:

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

Yes, I can use loops, but this is lame =)

+2
source share
2 answers

Just using kits:

 >>> 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']) >>> 
+5
source

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']) 
+8
source

Source: https://habr.com/ru/post/1304877/


All Articles