1

I am in an entry level programming class using Python and I was struggling to grasp a concept in our textbook.

# This code will cause an IndexError exception.
my_list = [10, 20, 30, 40]
index = 0
while index < 5:
    print(my_list[index])
    index += 1

This returns an IndexError as predicted, but I do not understand the exact reason why, but I do understand that the index set to < 5 in the loop is causing the error. I just need help understanding the logic behind the error not a solution to the error.

Matthew Smith
  • 508
  • 7
  • 22

1 Answers1

0

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_listyou 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)

Matthew Smith
  • 508
  • 7
  • 22
  • 1
    Why generate an index **at all**? `for value in my_list: print(value)` would be much more useful and concise, and much less error prone. And if you are going to generate an index, then a `for` loop is usually still the better option anyway, with `enumerate()` or `range()`. – Martijn Pieters Sep 30 '18 at 02:45
  • I agree. The options you have mentioned would be much more effective and concise. However, some of these concepts might be difficult for someone who is fairly new to Python. I will update my answer to include your suggestions. – Matthew Smith Sep 30 '18 at 02:53