Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Examples
  3. Remove Duplicates while Preserving Order

Lists · Python example

Remove Duplicates while Preserving Order

Use dictionary keys to deduplicate a list without losing the original order.

Open the compilerAll examples
intermediatelistsdictionariesdeduplication

A set removes duplicates but loses order. Dictionary keys also deduplicate, and since Python 3.7 they preserve insertion order.

example.py
values = [3, 1, 3, 2, 1, 4, 2]
unique = list(dict.fromkeys(values))

print("Original:", values)
print("Unique:", unique)

How the code works

  • Keys 3, 1, 2, and 4 are created as the list is scanned.
  • Repeated values do not create new keys.
  • The resulting list is [3, 1, 2, 4].

Key ideas

  • dict.fromkeys(values) creates keys in first-seen order.
  • list() converts the dictionary keys back to a list.
  • The original list is left untouched.

Try changing it

  • Compare the result with list(set(values)).
  • Deduplicate strings by their lowercase form.
  • Count occurrences at the same time with collections.Counter.

Related examples

beginner

List Statistics

Compute count, sum, minimum, maximum, and average for a list of numbers.

beginner

Set Operations

Compare two skill sets with union, intersection, and difference.

Previous exampleList StatisticsNext exampleTuple Unpacking

Expected output

Original: [3, 1, 3, 2, 1, 4, 2]
Unique: [3, 1, 2, 4]

Output is compared after trimming trailing whitespace on each line. Run the code to see it produced by CPython in your browser.

Practice next

Apply the same idea with automatic tests or browse a guided project.

ExercisesProjects