Sobes.tech
Junior

How would you make all list values unique?

sobes.tech AI

Answer from AI

Using a set, which by its nature stores only unique elements.

# Original list with duplicates
my_list = [1, 2, 2, 3, 4, 4, 5]

# Converting list to set to remove duplicates
unique_elements_set = set(my_list)

# Converting set back to list (if needed)
unique_list = list(unique_elements_set)

print(unique_list) # Output: [1, 2, 3, 4, 5] (order may vary)

You can also use a list comprehension with a check for membership to preserve the original order:

# Original list with duplicates
my_list = [1, 2, 2, 3, 4, 4, 5]

# Creating an empty list for unique elements
unique_list_ordered = []

# Iterating over the original list
for item in my_list:
    # Checking if the item is already in the list of unique elements
    if item not in unique_list_ordered:
        # If not, add it
        unique_list_ordered.append(item)

print(unique_list_ordered) # Output: [1, 2, 3, 4, 5] (order preserved)

For more efficient preservation of order with large lists, you can use dict.fromkeys (since Python 3.7, dictionaries preserve insertion order):

# Original list with duplicates
my_list = [1, 2, 2, 3, 4, 4, 5]

# Using dict.fromkeys to create a dictionary with unique keys
# and then converting the keys back to a list
unique_list_ordered_efficient = list(dict.fromkeys(my_list))

print(unique_list_ordered_efficient) # Output: [1, 2, 3, 4, 5] (order preserved)

The choice of method depends on whether you need to preserve the original order of elements. set is the most concise and efficient for removing duplicates but does not guarantee order. Methods with iteration and dict.fromkeys preserve order.