Programming Problems · Q6
Q.Write a program to read a list of elements. Modify this list so that it does not contain any duplicate elements, i.e., all elements occurring multiple times in the list should appear only once.
ChseodishaTextbookSubjective· 3mImportance★★★★★est
85% · 22/26 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →De-duplicate by rebuilding: walk the original list and append each element to a result list only if item not in result — every value keeps its first occurrence and its original position.
The idea. Removing duplicates while iterating over the same list is error-prone (deleting shifts the remaining indices under the loop). The clean pattern is to build a new list and let a membership test (not in) decide admission, then assign it back — the list is "modified" as asked, safely.
Program:
myList = eval(input("Enter the list: "))
unique = []
for item in myList:
if item not in unique: # first time we meet this value?
unique.append(item)
myList = unique # modified list without duplicates
print("List without duplicates:", myList)
Expected output (sample run):
Enter the list: [1, 2, 3, 2, 1, 4, 3]
List without duplicates: [1, 2, 3, 4]
Trace:
| item | already in unique? | unique afterwards |
|---|---|---|
| 1 | No | [1] |
| 2 | No | [1, 2] |
| 3 | No | [1, 2, 3] |
| 2 | Yes | [1, 2, 3] |
| 1 | Yes | [1, 2, 3] |
| 4 | No | [1, 2, 3, 4] |
| 3 | Yes | [1, 2, 3, 4] |
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.