0
votes

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

3 Answers

1
votes

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])
0
votes

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)
0
votes

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)