Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 2 of 10 · Data Types and Data Structures
Interview question

How do you remove duplicates from a list while preserving order? - Data Types and Data Structures List से duplicates कैसे remove करें जबकि order preserve रहे?

Answer
my_list = [1, 2, 2, 3, 1, 4, 2, 5]

# Method 1: dict.fromkeys() - BEST for Python 3.7+
result = list(dict.fromkeys(my_list))
print(result)  # [1, 2, 3, 4, 5]

# Method 2: Loop with set
seen = set()
result = []
for item in my_list:
    if item not in seen:
        result.append(item)
        seen.add(item)
print(result)  # [1, 2, 3, 4, 5]

# Method 3: List comprehension with walrus
seen = set()
result = [x for x in my_list if not (x in seen or seen.add(x))]
print(result)  # [1, 2, 3, 4, 5]
my_list = [1, 2, 2, 3, 1, 4]

# Method 1: dict.fromkeys()
result = list(dict.fromkeys(my_list))
# [1, 2, 3, 4]

# Method 2: Loop
seen = set()
result = []
for item in my_list:
    if item not in seen:
        result.append(item)
        seen.add(item)

Was this answer clear?