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 ???]
yield from
in python3.3+ to avoid the double loop:set([(yield from x) for x in d.values()])
. Note that doings=set((yield from x) for x in d.values())
yields almost the desired output... it contains an extraNone
that you have to remove sos.discard(None)
. (I believe there's already a question about this difference in behaviour between gen exps and list-comprehensions).