Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access two consecutive elements of a list in Python [duplicate]

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.

like image 344
swigganicks Avatar asked Dec 15 '13 03:12

swigganicks


2 Answers

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.

like image 71
thefourtheye Avatar answered Sep 18 '22 01:09

thefourtheye


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
like image 21
dansalmo Avatar answered Sep 19 '22 01:09

dansalmo