How to find the intersection of two lists in Python

4 Answers

0 votes
list1 = [1, 2, 3, 4, 5]
list2 = [6, 0, 2, 1, 7, 9]

set1 = set(list1)
set2 = set(list2)

intersection = list(set1 & set2)

print(intersection)




'''
run:

[1, 2]

'''

 



answered Apr 18, 2021 by avibootz
0 votes
list1 = [1, 2, 3, 4, 5]
list2 = [6, 0, 2, 1, 7, 9]

set1 = set(list1)
set2 = set(list2)

intersection = list(set(list1).intersection(list2))

print(intersection)




'''
run:

[1, 2]

'''

 



answered Apr 18, 2021 by avibootz
0 votes
list1 = [1, 2, 3, 4, 5]
list2 = [6, 0, 2, 1, 7, 9]

intersection = list(set(list1) & set(list2))

print(intersection)




'''
run:

[1, 2]

'''

 



answered Apr 18, 2021 by avibootz
0 votes
list1 = [1, 2, 3, 4, 5]
list2 = [6, 0, 2, 1, 7, 9]

intersection = [x for x in list1 if x in list2]

print(intersection)




'''
run:

[1, 2]

'''

 



answered Apr 18, 2021 by avibootz

Related questions

2 answers 128 views
1 answer 164 views
1 answer 175 views
1 answer 229 views
1 answer 166 views
2 answers 200 views
...