Error in while loop code for packing items

Peter Otten __peter__ at web.de
Thu Aug 18 08:29:21 EDT 2016


GP wrote:

The error and your second snippet aren't compatible, so I assume the 
exception is raised by

> for k in range(0,len(shelf)):
>       q1=ListDictItem[k]
>       q2 = ListDictItem.pop(k) #deletes the items that are packed.

> Error message:Traceback (most recent call last):
>   File "C:\Project\Python\ReadExcel-xlrd.py", line 201, in <module>
>     q1=ListDictItem[k]
> IndexError: list index out of range.

Take a moment to understand what happens if you iterate over the loop index 
like above:

items = ["foo", "bar", "baz"]

for k in range(len(items)):
    item = items[k]
    print(item)
    items.pop(k)

You start with k=0, item is set to items[0], i. e. "foo", that is printed 
and then items.pop(0) removes "foo" from the list which now looks like

items = ["bar", "baz"]

Now k=1, item is set to items[1], ie. "baz" ("bar" is never processed), 
"baz" is printed and then items.pop(1) removes "baz" and the list becomes

items = ["bar"]

Now k=2, so when you access items[2] from a list with only one item you get 
the IndexError. To make similar code work you need a while loop:

while items:
    item = items.pop(0)
    print(item)

However, when you really want to remove all items you instead assign a new 
empty list

for item in items:
    print(item)
items = []






More information about the Python-list mailing list