0

Trying to remove an element in a list:

a = [3,2,2,3,4,2,4]
b = 2

for i in range(0, len(a)):
    if a[i] == b:
        a.pop(i)
print(a)

getting the following error:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-5-dc2073ef875f> in <module>
      1 for i in range(0, len(a)):
----> 2     if a[i] == b:
      3         a.pop(i)
      4 print(a)

IndexError: list index out of range

Length of a is 7 and range(0, len(a)) also provides 7 values from 0 to 6, so can't understand the error.

  • 1
    When you pop an item the list gets smaller, even if you remove 1 item the code will throw an error for index 6. – Kantajit Aug 02 '21 at 07:07

0 Answers0