-1

I have this list but why am I getting this error as I am traversing through all elements in list .Please help me. Thank you

x = [43, 87, 23, 78, 87, 1, 3, 54]
for i in range(len(x)):
  if x[i] >50:
    x.remove(x[i])

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: list index out of range
mani varma
  • 31
  • 1
  • 4
  • 1
    You are removing items from the list while iterating through it... Maybe use a list comprehension instead `x = [i for i in x if i <= 50]` – alec Mar 19 '20 at 07:30
  • 1
    Does this answer your question? [How to remove list elements in a for loop in Python?](https://stackoverflow.com/questions/10665591/how-to-remove-list-elements-in-a-for-loop-in-python) – Jongware Mar 19 '20 at 07:48

1 Answers1

1

Indexes are zero based. So length -1 is limit.

You can just do this instead though:

c = True
while c:
    c = False
    for n in x:
        if n > 50:
            x.remove(n)
            c = True

You have the extra loop because if you don't you still end up with values over 50.

But lambdas:

x = list(filter(lambda n: n <= 50,x))  

or list comprehensions are easier:

x = [n for n in x if n <= 50] 

Also if you were to remove an entry from a list... it's length reduces.. So on each removal you would effectively have to re-evaluate. pop is the Python operator to remove an entry by the index. So, you'd end up with the far more cumbersome code like this:

x = [43, 87, 23, 78, 87, 1, 3, 54]
i = 0
while i < len(x):
    if x[i] > 50:
       x.pop(i)
       continue
    i=i+1
JGFMK
  • 8,425
  • 4
  • 58
  • 92