Problem No 16
Get unique elements preserving order
Medium≈ 16 minute session
Lesson guide
What this Python exercise practices
Get unique elements preserving order is a intermediate practice lesson that focuses on lists, iteration, filtering. It is designed to be solved in about 16 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- List values
- Basic indexing
Difficulty and time
- Level
- Intermediate
- Estimated time
- 16 minutes
Practice path
Summary
Return the unique elements from a list while keeping their first-seen order.
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]
Explanation
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 input 0
unique_preserve([5, 5, 6, 7, 6])
Sample output 0
[5, 6, 7]
Explanation 0
Keeps first 5, first 6, and first 7; ignores later duplicates.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.