Solution
With indices 0
, 1
, 2
and 3
you already accessed all 4 elements
of the list. There is no index 4
. Zero-based indexing means the last
index is always the length minus 1.
With this in mind, the problem is that you are expecting there to be five values in the list when there are only four. Change your code to the following...
my_list = [10, 20, 30, 40]
index = 0
while index < 4:
print(my_list[index])
index += 1
However, this would be 'hard-coding' the loop and if you were to modify the length of my_list
you would have to change the loop conditions. Therefore, I suggest you change the conditions to test the length of my_list
. Something like this would work...
my_list = [10, 20, 30, 40]
index = 0
while index < len(my_list):
print(my_list[index])
index += 1
Other Solutions
There are other more efficient ways to print out the contents of a list.
Looping through the contents of the list
for value in my_list:
print(value)
Using a starred expression (note this prints out the contents on the same line)
print(*my_list)