List index out of range occurred while removing Python list.

Asked 2 years ago, Updated 2 years ago, 37 views

L = [2,4,5,8,9,10,3]

length = len(L)

    for i in range(length):

     if L[i] < 5 :
        del L[i]


print(L)

I'm trying to extract a value less than 5 from the list, but I don't know why there's an error

Traceback (most recent call last):
  File "C:/", line 45, in <module>
    if L[i] < 5 :
IndexError: list index out of range

list python

2022-09-21 10:53

1 Answers


L = [2,4,5,8,9,10,3]
what_you_want = []
length = len(L)
for i in range(length):
    if L[i] < 5:
        what_you_want.append(L[i])


2022-09-21 10:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.