0
0
PythonHow-ToBeginner · 3 min read

How to Get Unique Elements from List in Python Easily

To get unique elements from a list in Python, use the set() function which removes duplicates by converting the list to a set. Then, convert it back to a list with list() if you need a list format.
📐

Syntax

Use set(your_list) to remove duplicates by converting the list to a set, which only keeps unique values. Then use list() to convert the set back to a list if needed.

  • your_list: The original list with possible duplicates.
  • set(): Removes duplicates by creating a set of unique elements.
  • list(): Converts the set back to a list.
python
unique_list = list(set(your_list))
💻

Example

This example shows how to get unique elements from a list of numbers. It converts the list to a set to remove duplicates, then back to a list to keep the list format.

python
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers)
Output
[1, 2, 3, 4, 5]
⚠️

Common Pitfalls

One common mistake is expecting the order of elements to stay the same after using set(). Sets do not keep order, so the result list may have elements in a different order than the original list.

To keep order while removing duplicates, use a loop or dictionary keys (Python 3.7+ preserves insertion order):

python
# Wrong way (order not preserved)
numbers = [3, 1, 2, 3, 2]
unique_wrong = list(set(numbers))
print(unique_wrong)  # Order may change

# Right way (order preserved)
unique_right = list(dict.fromkeys(numbers))
print(unique_right)  # Order kept
Output
[2, 3, 1] [3, 1, 2]
📊

Quick Reference

  • Remove duplicates, order not important: list(set(your_list))
  • Remove duplicates, keep order: list(dict.fromkeys(your_list))
  • Use list comprehension for conditions: [x for i, x in enumerate(your_list) if x not in your_list[:i]]

Key Takeaways

Use set() to quickly remove duplicates from a list.
Converting back to list() gives you a list of unique elements.
Sets do not keep the original order of elements.
Use list(dict.fromkeys(your_list)) to remove duplicates while keeping order.
Be careful with order if it matters in your program.