Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

AdvancedPhase 4 - Level 5: Logical & AppliedExample 10 of 14
unique-elements-only.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Get unique elements
8unique_arr = []
9seen = set()
10for element in arr:
11 if element not in seen:
12 unique_arr.append(element)
13 seen.add(element)
14
15print(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. 1

    Create seen and unique_arr.

  2. 2

    Append unseen values and add them to seen.

  3. 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.