A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-ways-to-remove-duplicates-from-list/ below:

Ways to remove duplicates from list in Python

Ways to remove duplicates from list in Python

Last Updated : 11 Jul, 2025

In this article, we'll learn several ways to remove duplicates from a list in Python. The simplest way to remove duplicates is by converting a list to a set.

Using set()

We can use set() to remove duplicates from the list. However, this approach does not preserve the original order.

Python
a = [1, 2, 2, 3, 4, 4, 5]

# Remove duplicates by converting to a set
a = list(set(a))

print(a)

Note: Using set() removes duplicates but does not guarantee the order of elements.

Let's explore other different ways to remove duplicates from list:

Using For Loop

To remove duplicates while keeping the original order, we can use a loop (for loop) to add only unique items to a new list.

Python
a = [1, 2, 2, 3, 4, 4, 5]

# Create an empty list to store unique values
res = []

# Iterate through each value in the list 'a'
for val in a:
  
    # Check if the value is not already in 'res'
    if val not in res:
      
        # If not present, append it to 'res'
        res.append(val)

print(res)

Note: This method preserves the original order but may be slower for large lists due to repeated membership checks ( ‘in’ operator).

Using List Comprehension

List comprehension is another way to remove duplicates while preserving order. This method provides a cleaner and one-liner approach.

Python
a = [1, 2, 2, 3, 4, 4, 5]

# Create an empty list to store unique values
res = []

# Use list comprehension to append values to 'res'
# if they are not already present
[res.append(val) for val in a if val not in res]

print(res)

Note: This method is concise but it is less efficient for large lists similar to the loop approach.

Using Dictionary fromkeys()

Dictionaries maintain the order of items and by using dict.fromkeys() we can create a dictionary with unique elements and then convert it back to a list.

Python
a = [1, 2, 2, 3, 4, 4, 5]

# Remove duplicates using dictionary fromkeys()
a = list(dict.fromkeys(a))

print(a)

Note: This method is generally faster than the loop method for larger lists.


Python - Ways to remove duplicates from list


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4