This is a very tricky problem to explain. I was playing around with Python's list methods, particularly the del
index object. I wanted to create a simple script that would create a list of integers from 1 to 100, and then a for loop which would delete the odd numbers from the list.
Here is the script I wrote:
def main():
num = list(range(1,101))
print(num)
for i in range(0,101):
del num[i]
print(num)
main()
Seems like it would work right? I thought so too, until I ran it.
I am not sure why, but when i
was passed to the del num[i]
index, the number itself doubled.
When I ran it, I received IndexError: list assignment index out of range
.
When I changed the parameters from range(0,101)
to range(0,10)
, I discovered that it deleted all the odd numbers from 1 to 20.
In other words, i
in the index is doubling when it shouldn't. Can I get some information about this?