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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With