Featured

How to Get Unique Elements from a List in Python (Easy Solutions)

How to Get Unique Elements from a List in Python (Easy Solutions)

Dharambir
Dharambir
1 January 2025 min read
ProgrammingPythonSoftware DevelopmentCoding TutorialsPython Tips

Imagine you have a list of restaurant names, maybe read from a file or entered manually, and you want to get rid of any duplicates. In Python, the easiest way to do this is by turning the list into a set. Sets automatically remove duplicates for you because they only store unique elements.

Example:

Let’s say your list looks like this:

restaurants = ["McDonald's", "Burger King", "McDonald's", "Chicken Chicken"]

You can convert this list to a set to remove the duplicates:

unique_restaurants = set(restaurants)
print(unique_restaurants)

Output:

{'Chicken Chicken', "McDonald's", 'Burger King'}

Notice that the set is not in the same order as the original list. That's because sets are unordered in Python. They don't maintain the sequence of elements.

Converting Back to a List

If you want to get your unique elements back in a list format, you can easily convert the set back to a list using Python’s built-in list() function:

unique_restaurants_list = list(unique_restaurants)
print(unique_restaurants_list)

Output:

['Chicken Chicken', "McDonald's", 'Burger King']

Now, the duplicates are gone, and you have a clean list to work with. You can do all the usual operations on this list, like looping, sorting, or filtering.

One-Liner Solution

If you want to combine everything into a one-liner, you can directly convert the list into a set and then back to a list in a single step:

unique_restaurants_list = list(set(restaurants))
print(unique_restaurants_list)

This removes all the duplicates and gives you a fresh list of unique restaurants.

Why This Works

  • Sets in Python are collections that don’t allow duplicates.
  • By converting a list to a set, you automatically eliminate any repeated elements.
  • Order doesn't matter for sets, so if the order of items is important to you, you might need to sort the list after removing duplicates.
#Pyhton programming#Programming languages#Python tutorial#Python tips#Python data structures#Set in Python
Share:
Dharambir

Dharambir