1

I'm working with Enthought canopy Python 2.7.9.
A very simple Python program that involves for, range, and len:

num = 10
mylist = range(num)
for i in range(len(mylist)):
  print "Size of mylist is %d" %(len(mylist))
  print "i=%d" %(i)
  print "mylist[%d] %d" %(i, mylist[i])
  mylist=mylist[:-1]

What puzzles me is that since the length of mylist has decreased to 5, why index i can still be 5, leading to the index error?

I know in Python a for-loop works with an iterable. But I do not know how this mechanism works in this example.

1
  • 1
    As a side note, you should generally use the more idiomatic for item in my_list. Check out enumerate() if you also need and index. Commented Jan 13, 2016 at 2:12

1 Answer 1

2

Never change the size of a list while iterating over it. Remove this line:

mylist=mylist[:-1] 

and it will work.

The length of the list is only determine once here:

for i in range(len(mylist)):

and i will take on all values from 0 through 9. When you change the size of the list later, the length will not be recalculated.

Sign up to request clarification or add additional context in comments.

1 Comment

To add to what Mike is saying here, at the start of the loop my_list is an identifier for a list of 10 items. Since you're using len() on that list, your loop will iterate 10 times. But inside the loop, you are reassigning the my_list identifier to point to a smaller and smaller list each iteration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.