Posts: 4,646
Threads: 1,493
Joined: Sep 2016
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?
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Posts: 8,156
Threads: 160
Joined: Sep 2016
Mar-22-2017, 05:46 AM
(This post was last modified: Mar-22-2017, 06:58 AM by buran.)
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']
Posts: 4,646
Threads: 1,493
Joined: Sep 2016
set might be a better way to store certain "lists" where order does not matter.
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Posts: 7,313
Threads: 123
Joined: Sep 2016
Mar-22-2017, 09:07 AM
(This post was last modified: Mar-22-2017, 09:07 AM by snippsat.)
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']
Posts: 331
Threads: 2
Joined: Feb 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).
Posts: 8,156
Threads: 160
Joined: Sep 2016
(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
|