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,452
  • 17
  • 21
swigganicks
  • 1,037
  • 2
  • 14
  • 26
  • 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

7

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
  • 221,210
  • 51
  • 432
  • 478
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
  • 10,936
  • 5
  • 55
  • 50