-1

How to iterate over a sequence, for example a list, and return a sub-sequence, for example a tuple? Sometimes this is referred to as "chunks" or "chunking".

for (a, b) in [1, 2, 3, 4, 5]:
   print('%s %s' % (a, b))

would print

1 2
2 3
3 4
4 5

The code example is not valid Python code. But it expresses what I want.

Can this be done within one expression (e.g. within a lambda)?

JamesThomasMoon
  • 6,169
  • 7
  • 37
  • 63

3 Answers3

2

Another examples how it could be done:

lst = [1, 2, 3, 4, 5]
for (a, b) in zip(lst, lst[1::]):
   print('%s %s' % (a, b))

Or using itertools:

from itertools import tee

i1, i2 = tee(iter([1, 2, 3, 4, 5]))
next(i2)
for (a, b) in zip(i1, i2):
   print('%s %s' % (a, b))
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0
l = [1, 2, 3, 4, 5, 6]
[(l[i], l[i+1]) for i in range(len(l)-1)]
#[(1, 2), (2, 3), (3, 4), (4, 5)]
Transhuman
  • 3,527
  • 1
  • 9
  • 15
0

You cannot do this quite as you wish; an iterator references each element of the iterable exactly once, but you reference it twice. The straightforward way would be

s = [1, 2, 3, 4, 5]
for idx in range(1, len(s)):
    print('%s %s' % (s[i-1], s[i]))

If you insist on extracting from the list only once, try this:

a = None
for b in [1, 2, 3, 4, 5]:
    if a:
       print('%s %s' % (a, b))
    a = b     # Save lower value for next iteration
Prune
  • 76,765
  • 14
  • 60
  • 81