NumPy Array :-
In Python, a Numpy array is a data structure provided by the Numpy library.
- A NumPy array is a way to store numbers in Python.
- It is faster and smaller than a normal list.
- You can do math on all the numbers at once.
- It has tools to cut, resize, and manage data
Example :-
import numpy as np array = np.array([10,20,30,40,50]) print(array)
Shifting Array Elements to Left :
1. With numpy.roll() Function (With Wrapping)
To shift elements in a NumPy array to the left, you can use the numpy.roll() function.
This moves all elements to the left.
Example :
import numpy as np array = np.array([10,20,30,40,50]) Newarray = np.roll(array, -1) print("Original Array:", array) print("Shifted Array:", Newarray)
Output :
Original Array: [10 20 30 40 50]
Shifted Array: [20 30 40 50 10]
2. Without Wrapping :
Without Wrapping refers to manually moving elements of a NumPy array to the left without using functions like np.roll
. It provides more control, And shifting is done manualy.
Example :
import numpy as np array = np.array([10, 20, 30, 40, 50]) shifted = np.empty_like(array) shifted[:-1] = array[1:] shifted[-1] = 0 print("Original Array:", array) print("Shifted Array:", shifted)
Output :
Original Array: [10 20 30 40 50] Shifted Array: [20 30 40 50 0]