List comprehension, check if item is unique

Stefan Bossbaly picture Stefan Bossbaly · May 19, 2015 · Viewed 15.9k times · Source

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

Answer

geckon picture geckon · May 19, 2015

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