Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Find identical items in multiple lists

Tags:

python

list

I have a list of an arbitrary number of lists, for instance:

[[1,2,3], [3,4,5], [5,6,7], [7,8,9]]

Now I would like a list containing all elements that are present in more than one list:

[3,5,7]

How would I do that?

Thanks!

like image 945
Mathias Loesch Avatar asked Jan 22 '10 09:01

Mathias Loesch


People also ask

How do you find common items between two lists?

Using sets Another approach to find, if two lists have common elements is to use sets. The sets have unordered collection of unique elements. So we convert the lists into sets and then create a new set by combining the given sets. If they have some common elements then the new set will not be empty.


1 Answers

I am still learning but would like to share my answer.

num_list1 = ['3', '6', '5', '8', '33', '12', '7', '4', '72', '2', '42', '13']
num_list2 = ['3', '6', '13', '5', '7', '89', '12', '3', '33', '34', '1', '344', '42']

result = [int(num) for num in num_list1 if num in num_list2)
print(result)

This prints:

[3, 6, 5, 33, 12, 7, 42, 13]

Comparing all elements in both lists and creating a new list with similar elements. And turning them into integers.

like image 141
Brad Rappa Avatar answered Nov 08 '22 01:11

Brad Rappa