Get the unique elements of a list
suggest changeLet’s say you’ve got a list of restaurants – maybe you read it from a file. You care about the unique restaurants in the list. The best way to get the unique elements from a list is to turn it into a set:
restaurants = ["McDonald's", "Burger King", "McDonald's", "Chicken Chicken"]
unique_restaurants = set(restaurants)
print(unique_restaurants)
# The three names, in an arbitrary order.
Note that the set is not in the same order as the original list; that is because sets are unordered. A dict keeps insertion order.
This can easily be transformed back into a list with Python’s built-in list function. The new list contains the unique names, not necessarily in the original order:
list(unique_restaurants)
# The three names, in an arbitrary order.
It’s also common to see this as one line:
# Removes all duplicates and returns another list
list(set(restaurants))
Now any operations that could be performed on the original list can be done again.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents