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???