In Python, an array can be subdivided into smaller sub-arrays, which can come in handy when working with larger datasets. This tutorial will show you how to divide an array into sub-arrays in Python.
First, let’s define an array:
1 |
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
In this case, arr
is an array with 10 elements.
Now let’s say we want to divide this array into three sub-arrays, each containing three elements. Here’s how we can do it:
Step 1: Determine the length of each sub-array
In this case, we want our sub-arrays to have a length of 3. We can assign this value to a variable:
1 |
sub_array_length = 3 |
Step 2: Determine the number of sub-arrays needed
To divide the main array into sub-arrays of equal length, we first need to determine how many sub-arrays we need. We can do this by dividing the length of the main array by the length of each sub-array:
1 |
num_sub_arrays = len(arr) // sub_array_length |
In this case, num_sub_arrays
will be 3
.
Step 3: Divide the array into sub-arrays
To divide the array into sub-arrays, we can use a loop to iterate over the main array and create a new sub-array at each step. Here’s an example of how we can do it:
1 2 3 4 5 |
sub_arrays = [] for i in range(num_sub_arrays): start = i * sub_array_length end = start + sub_array_length sub_arrays.append(arr[start:end]) |
Let’s go through what’s happening in the loop.
The start
variable is the starting index of each sub-array. For the first sub-array, start
is 0
, for the second sub-array it is 3
and for the third sub-array it is 6
.
The end
variable is the ending index of each sub-array. For the first sub-array, end
is 3
, for the second sub-array it is 6
and for the third sub-array it is 9
.
sub_arrays.append(arr[start:end])
appends the sub-array created by the slice arr[start:end]
to the sub_arrays
list.
Step 4: Print the sub-arrays
Let’s print out the sub-arrays to confirm the code is working as expected:
1 2 |
for i, sub_array in enumerate(sub_arrays): print(f"Sub-array {i+1}: {sub_array}") |
This will output:
Sub-array 1: [1, 2, 3] Sub-array 2: [4, 5, 6] Sub-array 3: [7, 8, 9]
And that’s it! You should now be able to divide an array into sub-arrays in Python.
As always, additional documentation can be found in the Python documentation.
Full code:
1 2 3 4 5 6 7 8 9 10 11 12 |
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sub_array_length = 3 num_sub_arrays = len(arr) // sub_array_length sub_arrays = [] for i in range(num_sub_arrays): start = i * sub_array_length end = start + sub_array_length sub_arrays.append(arr[start:end]) for i, sub_array in enumerate(sub_arrays): print(f"Sub-array {i+1}: {sub_array}") |