Python Forum
How do I split a large array into smaller sub-arrays? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How do I split a large array into smaller sub-arrays? (/thread-17326.html)



How do I split a large array into smaller sub-arrays? - codebeacon - Apr-07-2019

Hi,

I was wondering how I could split a large array into smaller chunks?

For example:

arr = ["hello", "my", "name", "is", "name", "hello", "my", "name", "is", "name2", "hello", "my", "name", "is", "name3"]
And I want to split the array into:
arr2 = [["hello", "my", "name", "is", "name"], ["hello", "my", "name", "is", "name2"], "hello", "my", "name", "is", "name3"]
If someone could please help, I would gladly appreciate it.
Thanks!


RE: How do I split a large array into smaller sub-arrays? - Gribouillis - Apr-07-2019

Use
d = 5
arr2 = [arr[i:i+d] for i in range(0, len(arr), d)]



RE: How do I split a large array into smaller sub-arrays? - perfringo - Apr-07-2019

This is list, not array:

>>> arr = ["hello", "my", "name", "is", "name", "hello", "my", "name", "is", "name2", "hello", "my", "name", "is", "name3"]
>>> type(arr)
list
If you want array in Python then:

>>> import array
>>> arr = array.array('d', [1, 2, 3])
>>> arr
array('d', [1.0, 2.0, 3.0])
>>> type(arr)
array.array
So, with high probability you want split list and not array. If length of chunks are known you can take advantage of slicing. If there is keyword on which list must be splitted then you can take advantage slicing combined with indexing the keyword.


RE: How do I split a large array into smaller sub-arrays? - codebeacon - Apr-08-2019

Thanks to everyone for replying, it's solved now.

Thanks.