0

Maybe it's too simple and I just didn't see my mistake.

while list_a[y] in list_a != list_a[-1]:
    print(y);y=y+1

returns IndexError: list index out of range

list_a looks like:

['00001', '00001', '00002', '00009', '0000G', '0000K', '0000K', '0000U', '0000U', '00013', '0001B', '0001D', '0001D', '0001L', '0001L', '0001N', '0001Q', '0001Q', '0001R', '0001U']

and my aim in the end is to delete some items from the list while iterating (that's why I want to use a while loop instead of for y in range(len(list_a))).

3
  • 1
    What do you think this condition does? It tests whether list_a[y] is in list_a (either true or indexerror) and then compares that (true) to list_a[-1]. Probably not what you wanted. Have you tried just using while y < len(list_a)? Commented Jun 19, 2014 at 7:51
  • in the end the loop does <something> until the last entry of the list everything correctly. Then it compares again and the error occurs Commented Jun 19, 2014 at 7:55
  • (Minor correction: in and != have the same precedence, so x in y != z actually evaluates like (x in y) and (y != z), similar to x < y < z.) Commented Jun 19, 2014 at 8:12

1 Answer 1

2

Think what you were trying for was:

while list_a[y] != list_a[-1]:
    ...

i.e. "while we're looking at the item that isn't equal to the last in the list". However, there will still be issues; what if items appear elsewhere in the list that are equal to the last item?

The general way to do this is to use a list comprehension to build a new list from the appropriate items in the old list:

list_b = [item for item in list_a if some_test(item)]
Sign up to request clarification or add additional context in comments.

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.