Python Forum

Full Version: How do I split a large array into smaller sub-arrays?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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!
Use
d = 5
arr2 = [arr[i:i+d] for i in range(0, len(arr), d)]
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.
Thanks to everyone for replying, it's solved now.

Thanks.