4

I have a list contains many elements. I want to slice it every 100 elements to a list of several lists.

For example:

>>> a = range(256)
>>> b = slice(a, 100)

b should then be [[0,1,2,...99],[100,101,102,...199],[200,201,...,255]].

What's the most pythonic and elegent way to do that?

tckmn
  • 57,719
  • 27
  • 114
  • 156
Xiao
  • 12,235
  • 2
  • 29
  • 36
  • @qqvc: No, not a dup of that. – abarnert Dec 18 '14 at 04:10
  • This is, however, a dup of literally dozens of questions. I can't find a canonical one that gives both good answers and compares and contrasts the two, so I'll pick one arbitrarily… – abarnert Dec 18 '14 at 04:11

1 Answers1

18

This should do the trick:

[a[i:i+100] for i in range(0, len(a), 100)]

range takes an optional third step argument, so range(0, n, 100) will be 0, 100, 200, ....

tckmn
  • 57,719
  • 27
  • 114
  • 156