python – Why do I get List index out of range when trying to add consecutive numbers in a list using for i in list?
python – Why do I get List index out of range when trying to add consecutive numbers in a list using for i in list?
-
In your
for
loop, youre iterating through the elements of a lista
. But in the body of the loop, youre using those items to index that list, when you actually want indexes.
Imagine if the lista
would contain 5 items, a number 100 would be among them and the for loop would reach it. You will essentially attempt to retrieve the 100th element of the lista
, which obviously is not there. This will give you anIndexError
.We can fix this issue by iterating over a range of indexes instead:
for i in range(len(a))
and access the
a
s items like that:a[i]
. This wont give any errors. -
In the loops body, youre indexing not only
a[i]
, but alsoa[i+1]
. This is also a place for a potential error. If your list contains 5 items and youre iterating over it like Ive shown in the point 1, youll get anIndexError
. Why? Becauserange(5)
is essentially0 1 2 3 4
, so when the loop reaches 4, you will attempt to get thea[5]
item. Since indexing in Python starts with 0 and your list contains 5 items, the last item would have an index 4, so getting thea[5]
would mean getting the sixth element which does not exist.To fix that, you should subtract 1 from
len(a)
in order to get a range sequence0 1 2 3
. Since youre using an indexi+1
, youll still get the last element, but this way you will avoid the error. -
There are many different ways to accomplish what youre trying to do here. Some of them are quite elegant and more pythonic, like list comprehensions:
b = [a[i] + a[i+1] for i in range(len(a) - 1)]
This does the job in only one line.
Reduce the range of the for loop to range(len(a) - 1)
:
a = [0, 1, 2, 3]
b = []
for i in range(len(a) - 1):
b.append(a[i] + a[i+1])
This can also be written as a list comprehension:
b = [a[i] + a[i+1] for i in range(len(a) - 1)]
python – Why do I get List index out of range when trying to add consecutive numbers in a list using for i in list?
When you call for i in a:
, you are getting the actual elements, not the indexes. When we reach the last element, that is 3
, b.append(a[i+1]-a[i])
looks for a[4]
, doesnt find one and then fails. Instead, try iterating over the indexes while stopping just short of the last one, like
for i in range(0, len(a)-1): Do something
Your current code wont work yet for the do something part though 😉