For loop ignores the first term python

I'm learning python however, I got an issue about for loop Here's my code:

arr=[1,2,3,4,5,6,7,8,9]

for i in arr:
    a=arr[i]
    print(a)

I expect to see 1, 2, 3, 4, 5, 6, 7, 8, 9. However for loop ignores first term "1". Why is that?

3 answers

  • answered 2022-01-23 02:26 prnvbn

    Either of the following loops will do what you are trying to do

    arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    for a in arr:
        print(a)
    
    
    for i in range(len(arr)):
        a = arr[i]
        print(a)
    

  • answered 2022-01-23 02:27 Raymond Kwok

    you can print element-by-element a list like this

    for i in arr:
        print(i)
    

    i is not an index, but the element itself.

    if you want i to be index, you need

    for i in range(len(arr)):
        print(arr[i])
    

  • answered 2022-01-23 02:38 rpontual

    The loop in python is "smarter" than in other languages. The "i" that you think is the array index is the array value. You do not need

    a=arr[i]
    print(a)
    

    You should just print "i"

    print(i)
    

    If instead you need the index, you can get it using the "enumerate" function. The syntax is as follows

    for index, value in enumerate(arr):
        print("arr[index] ", arr[index], 'is the same as the value', value)
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum