user3753064
user3753064

Reputation: 11

while loop - IndexError: list index out of range

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))).

Upvotes: 0

Views: 2994

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122024

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)]

Upvotes: 2

Related Questions