-2

I expected every element to go through the for loop, then the duplicate ones to be removed through the if loop.

num = [5, 7, 21, 7, 5, 7, 7, 5, 7 , 7]

for i in num:
    if num.count(i)!=1:
        num.remove(i)
print(num)

What I get:

[21, 7, 5, 7, 7]

What I expect:

[21, 5, 7]
ILS
  • 1,224
  • 1
  • 8
  • 14
  • Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – ILS Nov 10 '22 at 05:47
  • 1
    The list 'num' is being altered as you're iterating it. Adding values to a new list if it doesn't contain it rather than editing the original would avoid this. – Dan Walters Nov 11 '22 at 16:45
  • Does this answer your question? [Removing duplicates in lists](https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists) – gre_gor Nov 23 '22 at 15:41

2 Answers2

3

Since you are reducing the size of array while iterating on it. for i in num will check for the length of num. After 5 iterations (i=5), the length of num will become 5 and the loop will break.

It's better to always avoid mutating the list you're looping on.

Same result can also be achieved simply by:

num = list(set(num))
Shivam Nagar
  • 154
  • 5
1

list. remove(object) Removes the first item from the list which matches the specified value.

To solve your purpose we can utilize a data structure name set which have property to store multiple items in a single variable.

num = [5, 7, 21, 7, 5, 7, 7, 5, 7 , 7]
print(set(num))

If you want to go with your logic instead of using set data structure checkout this code

num = [5, 7, 21, 7, 5, 7, 7, 5, 7 , 7]

res = []
for i in range(len(num)):
    if num.index(num[i])==i:
        res.append(num[i])

print(res)

OR

num = [5, 7, 21, 7, 5, 7, 7, 5, 7 , 7]

res = []
for i in num:
    if i not in res:
        res.append(i)

print(res)
Davinder Singh
  • 2,060
  • 2
  • 7
  • 22