Breaking a list into chunks of size N

Hello there !
I’m trying to break a list into chunks of size N .
Here’s the code which I’ve written

julia> function chunk(arr,n)
       [arr[i * n:(i + 1) * n] for i in [(length(arr)+n-1)//n]]
       end

Can someone make it work !
Here’s what it’s intended to do.


my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] 
n = 4 //break at 4
Output: [[1, 2, 3, 4], [5, 6, 7, 8], [9]]
1 Like

Check out Iterators.partition(arr, n).

11 Likes

Here’s one way to do it.

chunk(arr, n) = [arr[i:min(i + n - 1, end)] for i in 1:n:length(arr)]
4 Likes