-1

I have the following problem. I have a list like:

>>> l = list(range(20))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> # What I want:
>>> [[0, 1, 2, 3], [3, 4, 5, 6], [6, 7, 8, 9] , ...]

How can I get my list into such k pieces with length 4 in the most pythonic way? I feel like I miss something obvious here. I am fully aware of How do you split a list into evenly sized chunks? but still have no clue...

Thanks in advance!

Community
  • 1
  • 1
Nikolai Tschacher
  • 1,639
  • 2
  • 17
  • 24

3 Answers3

2

A direct copy of an answer to question you have posted link to. The only change is the step in xrange - from n to n - 1:

def chunks(l, n):
    for i in xrange(0, len(l), n - 1):
        yield l[i:i + n]


list(chunks(range(20), 4))
[[0, 1, 2, 3], [3, 4, 5, 6], [6, 7, 8, 9], [9, 10, 11, 12], [12, 13, 14, 15], [15, 16, 17, 18], [18, 19]]
Maciej Gol
  • 15,394
  • 4
  • 33
  • 51
  • Finally someone who read the question correctly. Thanks for the answer and hell yes, I could have figured that one out for myself...Thanks sir! – Nikolai Tschacher Oct 13 '13 at 20:38
0
zip(*[iter(list(range(20)))]*4)
asdas
  • 23
  • 3
0
a = range(20)
b = [a[i:i+4] for i in xrange(0, len(a), 4)]
print b
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19]]