Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Get unique elements preserving order

Return the unique elements from a list while keeping their first-seen order.

Python practice16 minLists & TuplesIntermediateLast updated March 17, 2026

Problem statement

Write a function unique_preserve(lst) that takes a list and returns a new list with only the first occurrence of each element, preserving the original order. Do not use sorting. The function should handle any hashable elements (numbers, strings, tuples) and must preserve the order in which distinct elements first appear.

Task

Learn how to remove duplicates from a list without changing the relative order of first occurrences.

Examples

Basic example

Input

unique_preserve([1, 2, 2, 3, 1])

Output

[1, 2, 3]

1 appears first, then 2, then 3. Subsequent duplicates are ignored.

Input format

A single list (e.g., [1, 2, 2, 3]) passed to unique_preserve.

Output format

A list containing the first occurrence of each distinct element, in original order.

Constraints

You may assume elements are hashable. Do not change the input list in-place (return a new list). Aim for O(n) time and O(n) extra space.

Samples

Sample 1

Input

unique_preserve([5, 5, 6, 7, 6])

Output

[5, 6, 7]

Keeps first 5, first 6, and first 7; ignores later duplicates.