Python Forum

Full Version: python code begginer
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello I'm new in this page. I'm a beginner in python, and i have a question about this program.
I need to do this exercise:
Write a program to remove the duplicates in a list.
And i write this program:
n = [5, 3, 6, 7, 5, 5, 6, 7, 8, 3, 6, 5, 7, 8, 3, 4, 6, ]
for i in n:
    if n.count(i) > 1:
        n.remove(i)
print(n)
this is the answer: [5, 7, 3, 5, 7, 8, 3, 4, 6]
Can anyone tell my why this program doesn't work?
Sorry for my English, I'm learning. Thanks and regards
Hi,

simple mistake: you iterate over a list AND remove items from the list at the same time. Thus, you do not "catch" all items in the list.

Solution: create a 2nd list for the result and make use of the in operator to verify if an item is already in the new list. Or, more simple, use a set.

Regards, noisefloor
This question has been asked and answered in forum thread named removing duplicate numbers from a list
Hi Dear ,

You can simply use "set" for doing the same,

n = [5, 3, 6, 7, 5, 5, 6, 7, 8, 3, 6, 5, 7, 8, 3, 4, 6, ]
result = set(n)
result = list(result) 
print (result) # for python3 or for python2 go for print result