5

Possible Duplicate: Iterate a list as pair (current, next) in Python

While iterating a list, I want to print the current item in the list, plus the next value in the list.

listOfStuff = [a,b,c,d,e]
for item in listOfStuff:
    print item, <nextItem>

The output would be:

a b
b c
c d
d e
Community
  • 1
  • 1
ccwhite1
  • 3,625
  • 8
  • 36
  • 47

4 Answers4

4

The easiest way I found was:

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

for i,nexti in zip(a,a[1::]):
    print i,nexti
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
P2bM
  • 1,038
  • 6
  • 9
0
listOfStuff = ['a','b','c','d','e']
for i, item in enumerate(listOfStuff[:-1]):
    next_item = listOfStuff[i+1]
    print item, next_item
bigjim
  • 938
  • 1
  • 9
  • 18
0

How about:

for i in range(1, len(listOfStuff)):
    print listOfStuff[i - 1], listOfStuff[i]
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
0

This might do what you want:

def double_iter(iter):
    a = next(iter)
    for item in iter
        yield (a, item)
        a = item

double_iter(original_iter)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Greg Bowyer
  • 1,684
  • 13
  • 14