Reputation: 11
First of all, I have the answer to the question from mym teacher (it's from a lecture), and I see that stackoverflow has tons of questions like that. But my question isn't about the solution, but the meaning behind it:
Write a function that given a list of elements, return a new list with no duplicates.
def no_duplicate_list(lst):
new_lst = []
for i in lst:
if lst.count(i) == 1:
new_lst.append(i)
elif lst.count(i) > 1:
lst.remove(i)
return new_lst
print(no_duplicate_list([1,2,3,4,5, 3, 4, 2]))
I need to know, why when I remove an index from a list, let's say I got to the second index ( lst[1] = 2), when I remove it, it skips right after it to lst[3]4 and does not reach lst[2]=3.
Upvotes: 1
Views: 72
Reputation: 909
You should never modify the List as you are parsing it. Otherwise the iterator will be lost.
Here, indeed, this is useless since you will put the elements in your new List, that you will return.
The straightforward way is to take one element, check if you have it in your new List, if not, adding it.
def no_duplicate_list(lst):
new_lst = []
for i in lst:
if i not in new_lst:
new_lst.append(i)
return new_lst
Upvotes: 0
Reputation: 27008
You are modifying a list while iterating over it. That will invariably lead to undesired results.
Have you considered using a set?
def no_duplicate_list(lst):
return list(set(lst))
Here's a less efficient way without using a set:
def no_duplicate_list(lst):
new_list = []
for e in lst:
if not e in new_list:
new_list.append(e)
return new_list
Upvotes: 1