I need to access the n
and n+1
elements of a list. For example, if my list was [1,2,3,4,5]
and my nth element was 2
, I'd need the next element in the list, 3
.
Specifically, I need to access these elements in order to use them to look up a value in a matrix A
I have a for loop that's iterating over the list:
list = [1,2,3,4,5]
for i in list:
value = A[i,i+1] #access A[1,2], A[2,3], A[3,4], A[4,5]
the problem with this is that I can't do an i+1
operation to access the n+1
element of my list. This is my first time programming in Python and I assumed element access would be the same as in C/C++ but it's not. Any help would be appreciated.
You can use slicing operator like this
A = [1, 2, 3, 4, 5]
for i in range(len(A) - 1):
value = A[i:i+2]
The range
function lets you iterate len(A) - 1
times.
Enumerate can give you access to the index of each item:
for i, _ in enumerate(A[:-1]):
value = A[i:i+2]
If all you need are the pairs of data:
for value in zip(A, A[1:]):
value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With