6

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.

Ray
  • 2,472
  • 18
  • 22
swigganicks
  • 1,109
  • 2
  • 14
  • 28
  • unrelated: `A[i,i+1]` doesn't return `i`-th and `i+1`-th elements in C/C++ (unless you create a type in C++ that behaves that way, you can do it in Python too). The common interpretation, especially if `A` is a matrix is to return a single element from `i`-th row and `i+1`-th column e.g., `numpy` arrays do this. – jfs Dec 15 '13 at 04:28
  • The duplicate is about non overlapping chunk while this is overlapping. – user202729 Aug 16 '19 at 12:04
  • Better dup: https://stackoverflow.com/questions/5434891/iterate-a-list-as-pair-current-next-in-python – user202729 Aug 16 '19 at 12:08

2 Answers2

6

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.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 1
    another way is ... `A = [1, 2, 3, 4, 5]; print [(x,y)for x, y in zip(A[:-1], A[1:])]` – Hara Nov 13 '17 at 10:46
  • how do we set up the code so that the output is of the form [1,2], [3,4], [5,6]. .... – yash Feb 16 '21 at 09:05
2

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
dansalmo
  • 11,506
  • 5
  • 58
  • 53