Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python code begginer
#1
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
Reply
#2
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
Reply
#3
This question has been asked and answered in forum thread named removing duplicate numbers from a list
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Coding begginer Verner 1 1,304 Jan-24-2022, 11:27 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020