w3resource

Python: Remove duplicates from a list

Python List: Exercise-7 with Solution

Remove Duplicates from List

Write a Python program to remove duplicates from a list.

Visual Presentation:

Python: Remove duplicates from a list

Sample Solution:

Python Code:

# Define a list 'a' with some duplicate and unique elements
a = [10, 20, 30, 20, 10, 50, 60, 40, 80, 50, 40]

# Create an empty set to store duplicate items and an empty list for unique items
dup_items = set()
uniq_items = []

# Iterate through each element 'x' in the list 'a'
for x in a:
    # Check if the current element 'x' is not already in the set 'dup_items' (it's a duplicate check)
    if x not in dup_items:
        # If 'x' is not a duplicate, add it to the 'uniq_items' list
        uniq_items.append(x)
        # Add 'x' to the 'dup_items' set to mark it as a seen item
        dup_items.add(x)

# Print the set 'dup_items' which now contains the unique elements from the original list 'a'
print(dup_items) 

Sample Output:

{40, 10, 80, 50, 20, 60, 30} 

Explanation:

In the above exercise -

a = [10,20,30,20,10,50,60,40,80,50,40]  -> Creates a list called a that contains 11 integers.

dup_items = set()  -> Creates a new variable: an empty set called dup_items.

uniq_items = []  -> Creates a new variable: an empty list called uniq_items.

for x in a:
    if x not in dup_items:
        uniq_items.append(x)
        dup_items.add(x)

This line starts a 'for' loop that iterates over each element in the 'a' list, one at a time. The loop variable 'x' will take on the value of each element in the list during each iteration of the loop.

The if statement checks if the current element 'x' is not in the dup_items set. If this is true, it means the element is unique and should be added to the uniq_items list using the append method. Additionally, the element is added to the dup_items set using the add method to mark it as a duplicate.

print(dup_items)  -> This line prints the 'dup_items' set to the console using the print() function. The expected output would be {40, 10, 80, 50, 20, 60, 30}

Flowchart:

Flowchart: Remove duplicates from a list

Python Code Editor:

Previous: Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples.
Next: Write a Python program to check a list is empty or not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-7.php