0

Possible Duplicate:
What is the most “pythonic” way to iterate over a list in chunks?

Here is an example of my question:

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

Then if groupsize = 3, I want:

l1 = [(1,2,3),(4,5,6),(7,8,9)]

if groupsize = 4, then,

l1 = [(1,2,3,4),(5,6,7,8),(9,)]

Thanks.

Community
  • 1
  • 1
Rainfield
  • 1,082
  • 1
  • 13
  • 23

1 Answers1

2
In [1]: def group(l, size):
   ...:     return [tuple(l[i:i+size]) for i in range(0, len(l), size)]
   ...: 

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

In [3]: group(l, 3)
Out[3]: [(1, 2, 3), (4, 5, 6), (7, 8, 9)]

In [4]: group(l, 4)
Out[4]: [(1, 2, 3, 4), (5, 6, 7, 8), (9,)]

If you decide you want a generator, you can just change [] to () and get an equivalent of this answer (and this one) (except for conversion to tuple).

Community
  • 1
  • 1
Lev Levitsky
  • 55,704
  • 18
  • 130
  • 156