This is a very interesting idea so I ran it. Since I don’t normally use Python but have it on one of my laptops it took me a bit to figure out how this was setting up the files. The app ran but died on an index error at the end. Not sure why this happened as I follow only 400 others which doesn’t seem large to me but . . . Here is a screen shot showing the index failure:
Did a quick check on this but don’t have time to mess with it . . . [from Stack Overflow]
- In your
forloop, you're iterating through the elements of a list
a. But in the body of the loop, you're using those items to index that list, when you actually want indexes.
Imagine if the list
awould 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 list
a, which obviously is not there. This will give you an
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 won't give any errors.
- In the loop’s body, you’re indexing not only
a[i], but also
a[i+1]. This is also a place for a potential error. If your list contains 5 items and you're iterating over it like I've shown in the point 1, you'll get an
IndexError. Why? Because
0 1 2 3 4, so when the loop reaches 4, you will attempt to get the
aitem. Since indexing in Python starts with 0 and your list contains 5 items, the last item would have an index 4, so getting the
awould 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 sequence
0 1 2 3. Since you're using an index
i+1, you'll still get the last element, but this way you will avoid the error.
- There are many different ways to accomplish what you’re 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.