Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Data types & structuresJuniorVery commonPractical

Write a function that removes duplicates from a list while preserving the first occurrence order.

Answer

Use a set to remember values already seen and a list for ordered output. For each item, append it only when it is not already in the set, then add it to the set. This keeps the original first-occurrence order while giving average O(1) membership checks, so the whole pass is O(n) on average rather than repeatedly scanning the output list.

Strong answer includes

  • uses a set for average O(1) membership checks
  • preserves the first occurrence order
  • single pass with O(n) average time

Practical example

Single-pass ordered deduplication
Python
editable · browser sandbox
Result
Run the code to see the result.

seen provides fast membership checks while result preserves insertion order. This version assumes the input values are hashable.

Expected result: [3, 1, 2, 4]

#lists#sets#algorithms

Sources

The Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modulesThe Python TutorialPython Software Foundation · Baseline syntax, control flow, functions and module basics