Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension, check if item is unique

I am trying to write a list comprehension statement that will only add an item if it's not currently contained in the list. Is there a way to check the current items in the list that is currently being constructed? Here is a brief example:

Input

{     "Stefan" : ["running", "engineering", "dancing"],     "Bob" : ["dancing", "art", "theatre"],     "Julia" : ["running", "music", "art"] } 

Output

["running", "engineering", "dancing", "art", "theatre", "music"] 

Code without using a list comprehension

output = [] for name, hobbies in input.items():     for hobby in hobbies:         if hobby not in output:             output.append(hobby) 

My Attempt

[hobby for name, hobbies in input.items() for hobby in hobbies if hobby not in ???] 
like image 640
Stefan Bossbaly Avatar asked May 19 '15 17:05

Stefan Bossbaly


People also ask

How do you identify unique elements in a list?

Using Python's import numpy, the unique elements in the array are also obtained. In the first step convert the list to x=numpy. array(list) and then use numpy. unique(x) function to get the unique values from the list.


1 Answers

You can use set and set comprehension:

{hobby for name, hobbies in input.items() for hobby in hobbies} 

As m.wasowski mentioned, we don't use the name here, so we can use item.values() instead:

{hobby for hobbies in input.values() for hobby in hobbies} 

If you really need a list as the result, you can do this (but notice that usually you can work with sets without any problem):

list({hobby for hobbies in input.values() for hobby in hobbies}) 
like image 191
geckon Avatar answered Oct 13 '22 21:10

geckon