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 ???]
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.
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With