misheekoh
misheekoh

Reputation: 460

Slicing a list using List Comprehension

Let's say I want 20 integers from 1-20, put them in a list and for every 4 elements, group them. So I tried:

[(k[i::4]) for i in range(1,20)]

In theory, what I'm trying to do is for a range from 1-20, append i with step 4 into list k

It should look like [[1,2,3,4],[5,..,8]..[9,..,12].[13,..,16]...[17,..,20]

Upvotes: 0

Views: 566

Answers (4)

John La Rooy
John La Rooy

Reputation: 304355

>>> k = range(1, 21)
>>> list(zip(*[iter(k)] * 4))
[(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16), (17, 18, 19, 20)]

Upvotes: 0

A.J. Uppal
A.J. Uppal

Reputation: 19264

Try the following:

>>> k = range(0, 21)
>>> [[k[i:i+4] for i in range(1, 20, 4)]][0]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]
>>> 

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49330

You can simply create more range objects:

>>> [list(range(i, i+4)) for i in range(1, 21, 4)]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]

Upvotes: 2

Konstantin
Konstantin

Reputation: 25349

>>>[list(range(i,i+4)) for i in range(1, 20, 4)]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]

Upvotes: 1

Related Questions