Search code examples
pythonarrayslistindex-error

Can't figure out "IndexError: list index out of range" problem in Python


So, I'm trying to remove all numbers in array bigger than P (maximum) and can't figure out what's the problem with the code.

The code:

from array import array

A = array("i")
n = int(input("Number of elements: "))
A = [0] * n

print("Type elements of array: ")
for i in range(n):
    A[i] = int(input())

P = int(input("Max: "))

for i in range(n):
    if A[i] > P:
        A.pop(i)

print(A)

The result:

if A[i] > P:
   ~^^^
IndexError: list index out of range

Solution

  • Rather than trying to remove values from the list it's probably easier just to reconstruct it using a list comprehension and appropriate conditional check. Something like this:

    from array import array
    
    n = int(input('Number of elements: '))
    
    a = []
    
    for i in range(n):
        a.append(int(input(f'Element {i+1}: ')))
    
    m = int(input('Max: '))
    
    a = array('I', [e for e in a if e < m])
    
    print(a)
    

    Console (example):

    Number of elements: 5
    Element 1: 10
    Element 2: 20
    Element 3: 30
    Element 4: 40
    Element 5: 50
    Max: 35
    array('I', [10, 20, 30])