python for loop create a list

2447 views python
6

Ok guys, Why does this simple for-loop fail to fill a list? Here is what I have:

axx = []
for i in range(1,7):
  axx.append('ax'+str(i))
  print(axx[i])

I am getting an error:

Traceback (most recent call last):
  File "./bin_data2.py", line 57, in <module>
    print(axx[i])
IndexError: list index out of range

This should pretty simple and straightforward, isn't it? Sorry, coming from Fortran background!

answered question

1 Answer

11

You need i-1 while printing. Array is appended starting from 0 and i starts from 1. So, at first append, there is element at 0 but i has value of 1:

print(axx[i-1])

If you look into result from:

print(list(range(1,7)))

Output:

[1, 2, 3, 4, 5, 6]

posted this

Have an answer?

JD

Please login first before posting an answer.