Slice Multidimensional array in Python

We all know the concept of arrays – the easiest way to deal with a large amount of the same data type. Arrays are much easier to handle and provide us with a lot of functions to deal with. For example, if you want to store a big amount of data, you will definitely choose an array to do so instead of manually creating a list. A multi-dimensional one is an array consisting of multiple rows and columns. What is slicing?

Slicing in Python

Slicing is an in-built function in Python that uses an index and divides the given data in the format we want. For example, when we talk about a string `codespeedy`, you would like to deal with the first four characters, not with the entire string. The function we will use here is slicing. Assume you have saved this string inside str. You will execute str[0:3]. Hence, it will print the first four characters-code.

The sequence for slicing is [start:stop:jump]. The start is the index number from where you want to start, stop is the index where you want to stop, jump is the integer to skip some indexes between the start and stop.

You might have got an idea about slicing. In this tutorial, we will be dealing with the slicing of multi-dimensional arrays.

To do so, firstly create a multidimensional array using NumPy. Write the below code to get a better understanding of this topic:

```import numpy as np
arr1=np.array([[1,2,3,4,5],[6,7,8,9,10]])```

We have created a 2-D array. Let us try to print the array.

`print(arr1)`

It will result into:

```[[ 1  2  3  4  5]
[ 6  7  8  9 10]]```

Let us slice it into parts using the below techniques:

• When you want to print one row.

You can write print(arr1[0][:]) for 1st row or index 0

`print(arr1[0][:])`

It will result into:

`[1 2 3 4 5]`

or you can write print(arr1[1][:]) for 2nd row or index 1

`print(arr1[1][:])`

It results into:

`[ 6  7  8  9 10]`
• When you want alternate entries:

`print(arr1[::, ::2])`

This will result into:

```[[ 1  3  5]
[ 6  8 10]]```
• When you don’t want the end elements:

Sometimes you wish to remove the entries from front and end. To do so, you can write-

`print(arr1[:, 1:-1])`

This will remove the front and end entries of the array and result into-

```[[2 3 4]
[7 8 9]]```

You can implement this on 3-D array too using the same method.

I hope you find this tutorial helpful, feel free to comment and share your reviews! Thanks for reading.