Alvaro Gomez
Alvaro Gomez

Reputation: 360

For loop accessing two iteration positions in an array

I have the following code:

someList = ['a', 'b', 'c', 'd', 'e', 'f']

for i,j in enumerate(someList) step 2:
    print('%s, %s' % (someList[i], someList[i+1]))

My question is, is there any way to simplify the iteration over the array in order to avoid the enumerate part and still accessing two variables at a time?

Upvotes: 0

Views: 47

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

You can create two iterators, call next on the second and then zip which avoids the need to copy the list elements by slicing:

someList = ['a', 'b', 'c', 'd', 'e', 'f']

it1, it2 = iter(someList),  iter(someList)
next(it2)

for a,b in zip(it1,  it2):
   print(a, b)

Upvotes: 1

user2357112
user2357112

Reputation: 280837

for x, y in zip(someList, someList[1:]):
    print x, y

Standard technique.

Upvotes: 5

Related Questions