IndexError: list index out of range in an array Python

Dung Do Tien Aug 21 2021 142

Hi Guys, I'm a newbie in Python 3.8.2 and now I want to loop an array and print all items of it. See code below: 

def printArr(x):
    for i in x:
        print (x[i])
     
lst = [1,2,3,4,5,6,7,8,9,10]
printArr(lst)

But when run app I get an error IndexError: list index out of range

2
3
4
5
6
7
8
9
10
Traceback (most recent call last):
  File "main.py", line 7, in <module>
    check(lst)
  File "main.py", line 3, in check
    print (x[i])
IndexError: list index out of range

Anyone can explain to me, how can I resolve this bug?

Have 1 answer(s) found.
  • M

    Mohannad mostafa Aug 21 2021

    To loop an array you can use range() and len() methods to get the index of an array.

    def loopArr(x):
        for i in range(0,len(x)):
            print (x[i])
    
            
    lst = ["Red","Blue","Yellow","Green"]
    loopArr(lst)
    #OUTPUT
    Red
    Blue
    Yellow
    Green
    
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close