You are on page 1of 4

Practice | GeeksforGeeks | A computer science portal ... https://www.geeksforgeeks.org/batch/fork-data-scienc...

1 sur 4 11/04/2024 17:18


Practice | GeeksforGeeks | A computer science portal ... https://www.geeksforgeeks.org/batch/fork-data-scienc...

Arrays Slicing - DAP

In Python, array slicing is a common practice and it is the most used technique
for programmers to solve e�cient problems. Consider a python numpy array,
In-order to access a range of elements in an array, you need to slice an array.
One way to do this is to use the simple slicing operator i.e. colon(:)

With this operator, one can specify where to start the slicing, where to end, and
specify the step. List slicing returns a new list from the existing list.

Syntax:

Array[ Initial : End : IndexJump ]

The slicing done here is the same as that of the list.

Example 1:

Python3

import numpy as np
arr = np.array([1,2,3,4,5,6,7,8])
arr[3: ]

Output:

array([4, 5, 6, 7, 8])

So here we can see the slicing has started from the 4th index and has printed the
rest of the elements. The operation is same as that of a list.

Example 2:

Python3

print(arr[ : -3])
print(arr[3 : -3])

2 sur 4 11/04/2024 17:18


Practice | GeeksforGeeks | A computer science portal ... https://www.geeksforgeeks.org/batch/fork-data-scienc...

Output:

[1 2 3 4 5]
[4 5]

If we want to access a speci�c element or data from a 2 Dimension array we can


use the comma within the square brackets to indicate the row index in the �rst
part and the column index in the second part [row index, column index].

Let us see an example now.

Python3

arr = np.array([[1,2,3,4],[5,6,7,8],[8,7,6,5],[4,3,2,1]])
arr

Output:

array([[1, 2, 3, 4],
[5, 6, 7, 8],
[8, 7, 6, 5],
[4, 3, 2, 1]])

This is the 2D array which we will be using.

Python3

print(arr[ 3 , 1])
print()
print(arr[ 1: , 1:])

3 sur 4 11/04/2024 17:18


Practice | GeeksforGeeks | A computer science portal ... https://www.geeksforgeeks.org/batch/fork-data-scienc...

Output:

[[6 7 8]
[7 6 5]
[3 2 1]]

The �rst output we 3 because we were trying to get the 4th row(index 3) and 2nd
column(index 1)

The second output is a combination with slicing where we printed the array
starting from the 2nd row(index 1) and 2nd column(index 1) and the rest of the
elements which are coming in the upcoming indexes.

4 sur 4 11/04/2024 17:18

You might also like