0

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?

Alvaro Gomez
  • 350
  • 2
  • 7
  • 22

2 Answers2

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

Standard technique.

user2357112
  • 260,549
  • 28
  • 431
  • 505
1

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)
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321