简体   繁体   中英

Why do I get an IndexError: list index out of range

In my code I am getting an index error - IndexError: list index out of range. Could you please 1) explain why is this and then 2) make some corrections to my code? Thank you for your answer in advance

x = [1, 2, 3, 4, 5]

for i in range(len(x)):
    if x[i] % 2 == 0:
        del x[i]

Use a new list (comprehension) instead:

x = [1, 2, 3, 4, 5]

y = [item for item in x if not item % 2 == 0]
print(y)
# [1, 3, 5]

Or - considered "more pythonic":

y = [item for item in x if item % 2]

When you use del you reduce the size of your array but the initial loop goes through the initial size of the array, hence the IndexError.

If you want to delete items I recommend using list comprehension:

x = [1, 2, 3, 4, 5]

x_filtered = [i for i in x if i%2]

This is because you are removing objects inside of the loop, in other words making the list shorter.

Instead use this:

x = x[0::2]

To select every second value of the list

If you want all the even vaues, instead use a list generator:

x = [value for value in x in value%2 == 0]

You are deleting items from the very list you are iterating over. An alternative approach would be:

x = [1, 2, 3, 4, 5]
answer = [i for i in x if i % 2 != 0]

print(answer)

Outputs:

[1, 3, 5]
x = [1, 2, 3, 4, 5]

for i in range(len(x) -1, -1, -1):
    if x[i] % 2 == 0:
        x.pop(i)

"range function takes three arguments.

First is the start index which is [length of list – 1], that is, the index of last list element(since index of list elements starts from 0 till length – 1).

Second argument is the index at which to stop iteration.

Third argument is the step size. Since we need to decrease index by 1 in every iteration, this should be -1." - Source

I highly recommend list comprehension however in certain circumstances there is no point and removing through iteration is fine. Up to you~

use while loop instead of for loop if you want to delete some item.

    x = [1, 2, 3, 4, 5]
    i = 0
    while i<len(x):
        if x[i]%2==0:
            del x[i]
        i+=1
    print(x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM