What is happening that creates this "list index out of range" error

Screen Link:
https://app.dataquest.io/m/1009/lists-and-for-loops-practice-problems/5/incrementing-all-elements

My Code:

values = [16, 1, 7, 2, 19, 12, 5, 20, 2, 10, 10, 14, 17, 14, 1, 16, 19, 7, 9, 19]

# Write your answer below
for i in values:
    values[i] += 1

What I expected to happen:
it would add 1 to all elements of the list…

What actually happened:

IndexErrorTraceback (most recent call last)
<ipython-input-1-e6bd5dbc52d4> in <module>()
      3 # Write your answer below
      4 for i in values:
----> 5     values[i] += 1

IndexError: list index out of range

I’ve seen how to get the correct answer, but don’t understand what is happening that causes the error message when i enter the code this way. I’m not really stuck, I would just like to better understand what is going on.

1 Like

Use range(len(values)) to help you identify the position of the index.

for i in range(len(values)):
    values[i] += 1

If you want to use the method you suggest above, you may want to rename the first column to something like values_1 and run the following code:

values_1 = [16, 1, 7, 2, 19, 12, 5, 20, 2, 10, 10, 14, 17, 14, 1, 16, 19, 7, 9, 19]

values = [i+1 for i in values_1]
3 Likes

When you are entering this code it directly assigns you data in values to i. This makes the list index out of range as once it encounters 20 in your data there is no value more than that. So , when it increments 20 into 21, the list gets out of range.

In the answer provided, Range just defines the boundaries. Len fucntion will calculate the total elements and then range sets the range…

Run your code and the one given in the solution in this to have a better understanding.

http://www.pythontutor.com/visualize.html#mode=edit

3 Likes

thanks for the help!

1 Like

ohhhh perfect this is exactly what I’m looking for thank you!

1 Like

Oh great! :smile:

Kindly ensure that you mark the reply that solves the problem as the solution as this will help others in the community.

Happy learning @violaduck

2 Likes

@monorienaghogho i have the same doubt as above. And i wrote the same code as @violaduck . Still not getting this i am still stuck.

This code updates the same list that you are iterating over.
You can try any of the other methods suggested above when you create two different lists or you use list comprehension.

not clear. Thanks for replying

The problem is that you do not know the index.

For i in [2, 3, 4]:
             print(i)
Output 
2 
3
4

This is not the index of these numbers. So you cannot update. You can use range(len()) to get position of the index so that you can do your update

values[i] means update the number in value at this index i. In the above code, no way to get the index.

no the problem is not that. i know that values[i] means updating the number in value at index i. i dont know what the answer means by saying values[ -i - 1] , i mean we have to reverse values then why are we subtracting?. Go easy bro its hard to understand directly after learning lists and for loops.

:sweat_smile: Okay. I will send you a direct message.

1 Like

For i in values means take one item in the list values until the entire list is exhausted.

values[i] += 1 means go to the list values and increase the item at index i by 1.

When you write the code as shown below, it does not do the correct thing. For example when the number in values is 16, it updates the number at index 16. However 16 has an index number of 0. Because of this, some numbers are updated more than once and some numbers will not be updated at all.

The reason there is an index error is because the index for this list ends at 19. To check run len(values) - 1. However there is a value that is 20 on the list and python returns an index error.

values = [16, 1, 7, 2, 19, 12, 5, 20, 2, 10, 10, 14, 17, 14, 1, 16, 19, 7, 9, 19]

For i in values:
      value[i] += 1

I will change the number in 20 to 2 and 19 to 9 and run the code and print the result. You will see that the numbers are updated but not correctly. Because the index errors is coming from index 19 and 20

values = [16, 1, 7, 2, 9, 12, 5, 2, 2, 10, 10, 14, 17, 14, 1, 16, 9, 7, 9, 9]

for i in values:
    values[i] = values[i] + 1
    
values

Output:
[16, 2, 10, 3, 9, 13, 5, 3, 3, 12, 13, 15, 18, 14, 2, 17, 10, 8, 10, 9]

From the result, some numbers are not updated because they do not appear in the value list. This method is not doing what we expect correctly.

To solve correctly, we should use a method that gets the index (range(len(values)) and use it to update the list.

values = [16, 1, 7, 2, 19, 12, 5, 20, 2, 10, 10, 14, 17, 14, 1, 16, 19, 7, 9, 19]

for i in range(len(values)):
    values[i] += 1
 
values

Output
[17, 2, 8, 3, 20, 13, 6, 21, 3, 11, 11, 15, 18, 15, 2, 17, 20, 8, 10, 20]

Or using list comprehension:

values = [16, 1, 7, 2, 19, 12, 5, 20, 2, 10, 10, 14, 17, 14, 1, 16, 19, 7, 9, 19]

values = [i+1 for i in values]

Which gives the same result

7 Likes

For Problem 15: Adding All Matrix entries

matrix = [
    [0, 9, 5, 4],
    [8, 2, 3, 0],
    [1, 5, 3, 2]
]

def sum_list(a_list):
    return sum(a_list)

total = sum(map(sum_list, matrix))

For 13. Matrix

def create_list(nrow, ncol, values):
    matrix = np.arange(nrow*ncol)
    for index, value in enumerate(values):
        matrix[index] = value
    return matrix.reshape((nrow, ncol))

import numpy as np

# Test the function
values = [0, 9, 5, 4, 8, 2, 3, 0, 1, 5, 3, 2]
nrow = 3
ncol = 4
create_list(nrow, ncol, values)

# Ouputs
array([[0, 9, 5, 4],
       [8, 2, 3, 0],
       [1, 5, 3, 2]])

# Solve the problem
nrow = 7
ncol = 3

values = np.ones(nrow*ncol)

matrix_of_ones = create_list(nrow, ncol, values)

# convert np.array to list of list
matrix_of_ones = list(map(list, matrix_of_ones))

# Output
[[1, 1, 1], 
[1, 1, 1], 
[1, 1, 1], 
[1, 1, 1], 
[1, 1, 1], 
[1, 1, 1], 
[1, 1, 1]]

Cheers!

@pablajaspreet94 The python execution visualizer is so cool! Thanks a lot for sharing.

1 Like

Keep Learning. Happy to help my peers. @Deepa :smile:

Very clear explanation. Thumbs up

1 Like