Unique Elements Only
Create array with only unique elements.
AdvancedPhase 4 - Level 5: Logical & AppliedExample 10 of 14
unique-elements-only.py
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]
What's going on
Keep only first occurrence of each element.
Key Concepts:
Use set to track seen elements
Add to result if not seen
Preserves order of first occurrence
🔗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