NumPy left_shift() function

In Numpy, the left_shift() function is mainly used to perform the left shift operation.

  • The left_shift() function is mainly used in order to shift the bits of an integer to the left.

Syntax of numpy.left_shift():

The syntax required to use this function is as follows:

numpy.left_shift(x1, x2, /, out, *, where, casting='same_kind', order='K', dtype, ufunc 'left_shift')

As the internal representation of numbers is mainly in the binary format, thus left shift operation is equivalent to multiplying x1 by 2**x2.

With the help of this function, the bits are shifted to the left just by appending x2 number of 0s(zeroes) at the right of x1.


Let us now take a look at the parameters of this function:

  • x1
    This parameter is used to represent the input value and it is in the form of an array.
  • x2
    This parameter is used to indicate the number of bits to append at the right of x1. It must be a non-negative number. If x1.shape != x2.shape, then they must be broadcastable to a common shape and that shape becomes the shape of the output.
  • out
    This parameter indicates a location in which the result is stored. If this parameter is provided, it must have a shape that the inputs broadcast to. If this parameter is either not provided or it is None then a freshly-allocated array is returned.
  • where
    This parameter is used to indicate a condition that is broadcast over the input. At those locations where the condition is True, the out array will be set to the ufunc result, else the out array will retain its original value.

Returned Values:

This function will return x1 with bits shifted x2 times to the left. The returned value is a scalar if both x1 and x2 are scalars.

Example 1:

In the example below, we will illustrate the usage of left_shift() function:

import numpy as np

input_num = 40
bit_shift = 2
print ("The Input  number is: ")
print ("The Number of bit shift : ")
print(bit_shift )  
output = np.left_shift(input_num, bit_shift)  
print ("After the shifting of 2 bits to left : ")


The Input number is:
The Number of bit shift :
After the shifting of 2 bits to left :

Example 2:

Now we will show you a code snippet where we will apply left_shift() on to an input array:

import numpy as np

input_arr = [2, 8, 10] 
bit_shift =[3, 4, 5] 
print ("The Input array is: ")
print ("The Number of bit shift : ")
print(bit_shift )  
output = np.left_shift(input_arr, bit_shift)  
print ("After left shifting of bits,the output array is: ")


The Input array is:
[2, 8, 10]
The Number of bit shift :
[3, 4, 5]
After left shifting of bits,the output array is:
[ 16 128 320]
Follow Us On