Access two consecutive list items in Python

I need to access items nand a n+1list. For example, if my list was [1,2,3,4,5], and my n-th element was 2, I need the next item in the list 3.

In particular, I need to access these elements in order to use them to search for a value in matrix A

I have a for loop that repeats in a 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 is that I cannot perform an operation i+1to access an element of n+1my list. This is my first programming in Python, and I assumed that the access to the element would be the same as in C / C ++, but it is not. Any help would be appreciated.

+4
source share
2 answers

You can use a cutting operator like this

A = [1, 2, 3, 4, 5]
for i in range(len(A) - 1):
    value = A[i:i+2]

The function rangeallows you to repeat len(A) - 1time.

+5
source

Enumerate can give you access to the index of each element:

for i, _ in enumerate(A[:-1]):
    value = A[i:i+2]

If you only need a couple of data:

for value in zip(A, A[1:]):
    value
+1
source

All Articles