I was working on a list and I noticed something.
For example, this piece of code is deleting odd numbers from a list while looping over it.
numbers=[x for x in range (100)]
for nb in numbers:
if nb%2 == 1:
del numbers[numbers.index(nb)]
When you add a counter to see the total iterations you get:
numbers=[x for x in range (100)]
counter=0
for nb in numbers:
if nb%2 == 1:
del numbers[numbers.index(nb)]
counter +=1
The result is counter = 51.
However, if you add the operator list()
on the for loop:
numbers=[x for x in range (100)]
counter=0
for nb in list(numbers):
if nb%2 == 1:
del numbers[numbers.index(nb)]
counter +=1
This time the result is counter = 100.
I would like to know why and what is the role of the operator list()
here.
Note: if you print numbers
and list(numbers)
they are identical.