Python Forum
python code begginer - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: python code begginer (/thread-19313.html)



python code begginer - abdielG252 - Jun-22-2019

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


RE: python code begginer - noisefloor - Jun-22-2019

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


RE: python code begginer - perfringo - Jun-22-2019

This question has been asked and answered in forum thread named removing duplicate numbers from a list


RE: python code begginer - ankit - Jun-24-2019

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