Re: Splitting a list into even size chunks in python?

Discussion in 'Python' started by Arnaud Delobelle, Mar 27, 2013.

  1. On 27 March 2013 08:27, Peter Otten <> wrote:

    > Look again, for the grouper() recipe. For lists you can also use slicing:
    >
    >>>> items

    > ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    >>>> n = 3
    >>>> [items[start:start+n] for start in range(0, len(items), n)]

    > [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]


    Another way with islice (so it works for any iterable):

    >>> from itertools import islice
    >>> items = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    >>> n = 3
    >>> list(iter(lambda i=iter(items):list(islice(i, n)),[]))

    [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]

    Not too readable though :)

    --
    Arnaud
     
    Arnaud Delobelle, Mar 27, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John Ericson
    Replies:
    0
    Views:
    449
    John Ericson
    Jul 19, 2003
  2. Drew Olson
    Replies:
    33
    Views:
    1,075
    Drew Olson
    Dec 2, 2006
  3. Tore Aursand

    Splitting an array into "even" parts

    Tore Aursand, Nov 5, 2003, in forum: Perl Misc
    Replies:
    5
    Views:
    202
    Tore Aursand
    Nov 5, 2003
  4. Norah Jones
    Replies:
    0
    Views:
    133
    Norah Jones
    Mar 27, 2013
  5. Peter Otten
    Replies:
    4
    Views:
    186
    Chris Angelico
    Mar 28, 2013
Loading...

Share This Page