Unique Elements Only
Remove repeated list values while preserving first appearances in Python. Students pair a set for membership with a result list for stable output order.
1# Take array2n = int(input("Enter array size: "))3arr = []4for i in range(n):5 arr.append(int(input(f"Element {i+1}: ")))67# Get unique elements8unique_arr = []9seen = set()10for element in arr:11 if element not in seen:12 unique_arr.append(element)13 seen.add(element)1415print(f"Original: {arr}")16print(f"Unique elements: {unique_arr}")
Output
Enter array size: 6 Element 1: 1 Element 2: 2 Element 3: 2 Element 4: 3 Element 5: 1 Element 6: 4 Original: [1, 2, 2, 3, 1, 4] Unique elements: [1, 2, 3, 4]
In this one
- Deduplicate in stable order
- Track membership with a set
- Retain first occurrences
How it works
- 1
Create seen and unique_arr.
- 2
Append unseen values and add them to seen.
- 3
Skip later duplicates and display the result.
Edge cases
Is a repeated value removed entirely?
Is a repeated value removed entirely?
No. Its first occurrence remains.
Is the result sorted?
Is the result sorted?
No. It follows first appearance.
What's going on
seen records which values have already appeared. A new value is appended to unique_arr and added to seen together.
Repeated occurrences are skipped, but the first occurrence remains. Thus [3, 1, 3, 2] becomes [3, 1, 2]. Unique here means deduplicated values, not values that appeared exactly once. The original list is retained for comparison.
Is a repeated value removed entirely? No. Its first occurrence remains.
Is the result sorted? No. It follows first appearance.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why use both a list and a set?
Pick an answer to check it.
Question 2
Is a repeated value removed entirely?
Pick an answer to check it.
Questions people ask
Is a repeated value removed entirely?
No. Its first occurrence remains.
Is the result sorted?
No. It follows first appearance.
Why use both a list and a set?
The list preserves order while the set tracks membership.
๐Related Content
- ๐
Phase 4 - Learn Concepts
Review Phase 4 concepts and explanations
- ๐
Phase 4 - Quiz
Test your Phase 4 understanding with quiz questions
- ๐ป
Phase 4 - All Practice Problems
Explore all practice problems for Phase 4
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum