Rangooski Rangooski - 5 months ago 15
Python Question

Python : Split list in a specific way?

Let's say I have a list

A


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


I would like to create a new list (say
B
) using the above list in the following order.

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


i.e. the first 3 numbers as
A[0,1,2]
and the second 3 numbers as
A[2,3,4]
and so on.


I believe there is a function in
numpy
for such a kind of operation.

Answer

Simply use Python's built-in list comprehension with list-slicing to do this:

>>> A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> size = 3
>>> step = 2
>>> A = [A[i : i + size] for i in range(0, len(A), step)]

This gives you what you're looking for:

>>> A
[[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, 10]]

But you'll have to write a couple of lines to make sure that your code doesn't break for unprecedented values of size/step.