Python Forum
common elements of a list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: common elements of a list (/thread-2503.html)



common elements of a list - Skaperen - Mar-22-2017

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?


RE: common elements of a list - buran - Mar-22-2017

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']



RE: common elements of a list - Skaperen - Mar-22-2017

set might be a better way to store certain "lists" where order does not matter.


RE: common elements of a list - snippsat - Mar-22-2017

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']



RE: common elements of a list - zivoni - Mar-22-2017

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).


RE: common elements of a list - buran - Mar-22-2017

(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