Home > Back-end >  For loop stops iterating for no apparent reason
For loop stops iterating for no apparent reason

Time:08-18

I want to remove duplicates from the list, so I created the simplest possible exapmple here:

   alist = [1,1,1,1,2,3]
   
   for num in alist:
       if alist.count(num) > 1:
           alist.remove(num)
   
   print(alist)

Output: [1, 1, 2, 3]

It seems the iteration stops despite alist.count(num) being equal to 2. Please help.

CodePudding user response:

Simply doing this should work:

alist = [1,1,1,1,2,3]
alist = list(set(alist))
print(alist)

>>>
[1, 2, 3]

CodePudding user response:

Removing elements in alist while also being under iteration is a bad idea. You may use this instead.

alist = [1,1,1,1,2,3]
blist = list(set(alist))

CodePudding user response:

The issue is that you are only removing one duplicate per number, instead of removing all duplicates for that number. The modified code looks like this:

   alist = [1,1,1,1,2,3]
   
   for num in alist:
       while alist.count(num) > 1:
           alist.remove(num)
   
   print(alist)

Gets the following result:

>> [1, 2, 3]

However if order does not matter a more concise way would be to use a set and then turn it back into a list:

>> alist = [1,1,1,1,2,3]
>> print(list(set(alist)))
>> [1, 2, 3]
  • Related