Python Forum

Full Version: common elements of a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
given 2 or more lists, i'd like to get a list of the common elements.  if the order gets re-arranged that is ok.

a=['apple','banana','cherry','lemon','orange']
b=['car','lemon',80,443,'python','banana','yellow']
c=commonlist(a,b)
print(c)
Output:
['banana','lemon']
is there an easy way to do that?
Convert lists to sets and check for intersection

a=['apple','banana','cherry','lemon','orange']
b=['car','lemon',80,443,'python','banana','yellow']
c=list(set(a) & set(b)) # of course converting back to list is optional
print c
Output:
['lemon', 'banana']
set might be a better way to store certain "lists" where order does not matter.
One with list comprehension.
>>> a = ['apple','banana','cherry','lemon','orange']
>>> b = ['car','lemon',80,443,'python','banana','yellow']
>>> [i for i in a if i in b]
['banana', 'lemon']
not change to difference.
>>> [i for i in a if i not in b]
['apple', 'cherry', 'orange']
# sets
>>> list(set(a) - set(b))
['cherry', 'apple', 'orange']
List comprehension is more universal, as sets work only with hashable items. Sometimes one could be bitten with a fact that immutability doesnt guarantee hashability (usually with tuples - while (1, [2]) is tuple and therefore immutable, it is not hashable).
(Mar-22-2017, 09:44 AM)zivoni Wrote: [ -> ]List comprehension is more universal, as sets work only with hashable items. Sometimes one could be bitten with a fact that immutability doesnt guarantee hashability (usually with tuples - while (1, [2]) is tuple and therefore immutable, it is not hashable).

Good point regarding hashability of elements of the set