-1

I write the follwing code in order to sort a list by the number of digits in a number:

lst = [1, 4444, 333, 7777777, 22, 1, 9, 55555]

num_digits = 1
sorted = []
for num in lst:
    if len(str(num)) == num_digits:
        sorted.append(num)
        print(sorted)
        print(lst)

And the result is:

[1]
[1, 4444, 333, 7777777, 22, 1, 9, 55555]
[1, 1]
[1, 4444, 333, 7777777, 22, 1, 9, 55555]
[1, 1, 9]
[1, 4444, 333, 7777777, 22, 1, 9, 55555]

But when I write:

num_digits = 1
sorted = []
for num in lst:
   if len(str(num)) == num_digits:
      sorted.append(num)
      lst.remove(num)
      print(sorted)
      print(lst)

I get this result:

[1]
[4444, 333, 7777777, 22, 1, 9, 55555]
[1, 1]
[4444, 333, 7777777, 22, 9, 55555]

I don't understend why the code ignores the 9 when i add a remove() command???

Amit Oren
  • 1
  • 1
  • 1
    Thumb rule: **Never** mutate the list while iterating through it. – Ch3steR Apr 01 '20 at 07:25
  • It seems like the iterator has been invalidated. DO NOT change the list while iterating. – MyBug18 Apr 01 '20 at 07:25
  • 1
    Does this answer your question? [strange result when removing item from a list](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list) – dspencer Apr 01 '20 at 07:30

1 Answers1

0

You can not change the list you are 'looping' inside the loop. This disrupts the looping and you get weird results. Because you are comparing with == you don't need to remove items from lst. Just continue with the next num_digits.

lst = [1, 4444, 333, 7777777, 22, 1, 9, 55555]

sorted = []

for num_digits in range(10):
    for num in lst:
        if len(str(num)) == num_digits:
            sorted.append(num)
            print(sorted)


[1]
[1, 1]
[1, 1, 9]
[1, 1, 9, 22]
[1, 1, 9, 22, 333]
[1, 1, 9, 22, 333, 4444]
[1, 1, 9, 22, 333, 4444, 55555]
[1, 1, 9, 22, 333, 4444, 55555, 7777777]
Mace
  • 1,355
  • 8
  • 13