Error in while loop code for packing items

GP gyan.am010 at gmail.com
Thu Aug 18 09:10:55 EDT 2016


On Thursday, August 18, 2016 at 5:59:43 PM UTC+5:30, Peter Otten wrote:
> 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 = []


Thanks Peter for the information. It helps to find the source of error .

What I wanted was to remove the items that was packed so that the code  can check for the next items that match the criteria and then pack those and delete them  and keep on repeating until all the items are packed. This is where I am getting stuck.



More information about the Python-list mailing list