-1

For example, I have simple list like this:

l = [1,2,3,4,5,6,7,8,9]

I want to iterate over it in groups of 3 elements:

1,2,3
4,5,6
7,8,9

What is simplest way to do it?

user3654650
  • 5,283
  • 10
  • 27
  • 28
  • IMO the best way to do this is described here, and is adapted from a recipe in the `itertools` documentation: http://stackoverflow.com/a/434411/2073595. – dano Jun 03 '14 at 04:31

3 Answers3

5

Tricky, but well-known way (from itertools grouper recipe):

>>> zip(*[iter(l)] * 3))
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

It can be written as

>>> it = iter(l)
>>> zip(it, it, it)
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

Full explanation here: How does zip(*[iter(s)]*n) work in Python?

Community
  • 1
  • 1
vaultah
  • 44,105
  • 12
  • 114
  • 143
  • That's nice. Could you give one or two sentences what is happening here. – Marcin Jun 03 '14 at 04:27
  • Careful though. Since `zip` truncates to the shortest of the sequences, if `l` isn't divisible by `3` exactly, you'll lose a couple trailing elements. That's why the grouper recipe uses `izip_longest`. Just for fun, a couple days ago, on a duplicate question to this, [I wrote up a whole bunch of different ways to do this](http://stackoverflow.com/a/23926929/748858) each with _slightly_ different output and different input assumptions. – mgilson Jun 03 '14 at 05:16
2

You can do it as:

l = [1,2,3,4,5,6,7,8,9]

result = [l[i:i+3] for i in range(0,len(l),3)]

>>> print result
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

>>> for i in result:
...     print(i)
... 
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
sshashank124
  • 31,495
  • 9
  • 67
  • 76
2

You could write simple generator

def group_gen(lst, n):
    for i in range(0,len(lst), n):
        yield l[i:i+n]


for a,b,c in group_gen(l, 3):
    print(a,b,c)

Results in:

1 2 3
4 5 6
7 8 9
Marcin
  • 215,873
  • 14
  • 235
  • 294