+ 1
Why does it print five?
my_list = ['one', 'two', 'three', 'four', 'five'] my_list_len = len(my_list) for i in range(0, my_list_len): print(my_list[i])
2 Answers
+ 9
because len counts the amount in list, which is five. then with for i in range you're telling it to print from 0 to len(5). so it prints out all 5 in the list
+ 4
Complement to @Ahri Fox answer: the function range(a,b) return a list from a to b, with a and without b, so it's [0,1,2,3,4] corresponding to the five indexes of the 'my_list' array: the first element is indexed to zero, the second to one, and so on until the nth ( 5th ) which has index n-1 ( 4 ).
Starting indexes with 0 make sens in computer logic, but is a trap for the user/coder. I think a good way to understand this counting way, is to thing to a building and its floors, which are counted in the same way, with ground floor at level 0, floor 1 at level 0,... starting count from zero ;)