Example 01
1 2 3 4 | my_list = [ 'red' , 'green' , 'yellow' ] lucky_number = 3 if lucky_number > 0 : print my_list[lucky_number] |
Reason: The IndexError happens when an index does not have a valid value. In Python, the index of a list starts at 0 and thus valid indices for a list of length 3 are 0, 1, and 2. The variable lucky_number is 3 and my_list[lucky_number] equals my_list[3], resulting in an IndexError.
Example 02
1 2 3 4 | my_list = range ( 3 ) lucky_number = 3 if lucky_number > 0 : print my_list[lucky_number] |
Reason: The function call range(3) produces the list [0, 1, 2] and 3 is not included. Valid indices are thus 0, 1, and 2. The variable lucky_number is 3 and my_list[lucky_number] equals my_list[3], resulting in an IndexError.