Python program to remove duplicates from a list

Description: Write a Python program to remove the duplicate items from a list.

Rules and hints:

  • A set keeps only unique values, but it does not keep the order.
  • dict.fromkeys() keeps the order of the first appearance.

Python program to remove duplicates from a list

items = [1, 2, 2, 3, 4, 4, 5]

unique_sorted = sorted(set(items))
unique_ordered = list(dict.fromkeys(items))

print(unique_sorted)
print(unique_ordered)

Output:

Tutorials Class - Output Window

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

How it works

  • set(items) removes the duplicates, and sorted() makes a sorted list of it.
  • A dictionary cannot have duplicate keys, and in Python 3.7+ it keeps the insertion order. So dict.fromkeys(items) followed by list() keeps the first order.

Related: Python Sets and Python Dictionary.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.