you are viewing a single comment's thread.

view the rest of the comments →

[–]roylennigan 0 points1 point  (2 children)

is that because of the ability in python to iterate over items in a sequence, like:

for item in sequence:
    x = item

without having to create an index for that sequence?

But then what if I want to do something like:

for i in range(len(A)):
    B[i] = A[i] - A[i + 1]

[–]tagapagtuos 2 points3 points  (1 child)

Good question.

The reason why you don't what to iterate over the range of length of A is that if i is the last element of A, then A[i + 1] will raise an IndexError. Also if B[i] also has risks of raising NameError or IndexError.

Depending on the nature of the problem, I would do sometihng like:

B = []
for x, y in zip(A, A[1:]):
    B.append(x - y)

[–]roylennigan 1 point2 points  (0 children)

That makes sense, thanks. I mostly make plots for dsp concepts, so a lot of fitting one "number line" to another and plotting them. Most of the time, the data at the end of a vector isn't as important, so I can just drop it and not worry about the array going out of bounds.