0

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 ?

0

3 Answers 3

5

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

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.