tuna
tuna

Reputation: 6351

list index out of range error while iterating in list length

I have the following code, which sortings_list consist of 2 items like

sortings_list = ['code', 'name']


for i in xrange(0, len(sortings_list)):
        if sortings_list[i] == '-%s' % field:
            sortings_list.pop(i)

Any ideas ?

Upvotes: 0

Views: 89

Answers (3)

Hai Vu
Hai Vu

Reputation: 40688

You are better off using list comprehension because indexing is messy. With Python, you don't need to index a list in most cases. That being said, if you still insist on using your solution:

for i in xrange(len(sortings_list) - 1, -1, -1):
    if ...:
        sortings_list.pop(i)

That is, you start from the end of the list and traverse backward. That way, all the indexing still works. Again, I highly recommend against doing things this way. Go with list comprehension which Martijn Pieters offers.

Upvotes: 0

John Gordon
John Gordon

Reputation: 33310

You're calling pop() on the first item which removes it, and now the list only has one element.

Then you try to iterate to the second item, which doesn't exist anymore.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121544

You are removing items from a list while iterating, if you remove the first item then the second item's index changes. Use a list comprehension instead:

sortings_list = [elem for elem in sortings_list if not elem == '-%s' % field]

Upvotes: 5

Related Questions