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
  • 330
  • 2
  • 5
  • 21

2 Answers2

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

Standard technique.

user2357112
  • 235,058
  • 25
  • 372
  • 444
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
  • 168,988
  • 22
  • 228
  • 312