I am trying to use list comprehension with this exercise:
def unique_values(my_dictionary):
list_unique_value =
list_unique_value = [value for value in my_dictionary.values() if value not in list_unique_value]
return len(list_unique_value)
It works if I use the following:
def unique_values(my_dictionary):
for value in my_dictionary.values():
if value not in list_unique_value:
list_unique_value.append(value)
return len(list_unique_value)
Could someone please tell me what I’m doing wrong?
When we are using a comprehension we cannot poll the list we are building so it is not suited to this type of problem. You’ll need to use the conventional means to generate a new list of unique values. This is not unlike a set, but for the ordered nature. Sets are not ordered.
a = set(my_dictionary.values())
But, save doing it this way for when it actually means something. Stick with the conventional iterative approach so you get the practice and gain deeper understanding of the process. This stuff is confusing enough, as it is. We don’t want to toss it aside, just yet, or ever.