Array Slicing in Python
Slicing in Python allows you to extract a portion of an array by specifying a range of indices.
The basic syntax for slicing is:
array[start:end]
Here:
start is the index where the slice begins (inclusive).
end is the index where the slice ends (exclusive).
You can also include a step value to skip elements:
array[start:end:step]
Some important points:
If you omit the start, it defaults to 0.
If you omit the end, it defaults to the length of the array.
If you omit the step, it defaults to 1.
This gives you a lot of flexibility to access parts of arrays easily.
Program:
Slice Elements from a NumPy Array
Get elements starting from index 1 up to (but not including) index 5 from the given array:
import numpy as np
# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5, 6, 7])
# Slice elements from index 1 to 4 ex(ind 5 is not included)
result = arr[1:5]
print(result)
Output:
[2 3 4 5]
Program:
import numpy as np
# Create a NumPy array
array = np.array([1, 2, 3, 4, 5, 6, 7])
# Slice elements from index 4 to the end
result = array[4:]
print(result)
Output:
[5 6 7]
Program:
import numpy as np
numbers = np.array([1, 2, 3, 4, 5, 6, 7])
# Slice from start to index 4 (not included)
print(numbers[0:4])
Output:
[1 2 3 4]
Negative Slicing in NumPy
You can use negative indices to slice elements starting from the end of an array.
Program:
Slice the array starting from the 3rd element from the end up to (but not including) the last element:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[-3:-1])
Output:
[5 6]
In this example, -3 refers to the element 5 (third from the end), and -1 refers to the element just before the last (but the end index is exclusive)
STEP in Slicing
The step value in slicing specifies the interval between elements that you want to select.
Program:
Select every second element between index 1 and index 5:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5:2])
Output:
[2 4]
Program:
import numpy as np
# Create a NumPy array
array = np.array([1, 2, 3, 4, 5, 6, 7])
# Print every second element
print(array[::2])
Output:
[1 3 5 7]
Slicing 2 D Array
Program:
import numpy as nparray
arr = np.array([[1, 2, 3, 4, 5],[6,7,8,9,10]])
# Slice elements from index 1 to 3 (index 4 not included) in the second row (index 1)
result = arr[1, 1:4]
print(result)
Output:
[7 8 9]
Program:
From both elements, return index 2:
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 2])
Output:
[3 8]
Program:
import numpy as np
# Create a 2-D array
arr = np.array([[1, 2, 3, 4, 5],[6 7 8 9 10]])
# Slice elements from index 1 to 3 (index 4 is not included) from both rows
result = arr[0:2, 1:4]
print(result)