How to Shift Numbers in Python?

Estimated read time 2 min read

To shift numbers in Python, you can use slicing and concatenation operations to rearrange the order of elements in a list or array. Here are a few examples:

  1. Shifting a List by One Position to the Left:
my_list = [1, 2, 3, 4, 5]

# Shift the list by one position to the left
shifted_list = my_list[1:] + [my_list[0]]

print(shifted_list)
# Output: [2, 3, 4, 5, 1]

In this example, we define a list my_list containing 5 elements.

We slice the list using my_list[1:] to select all elements from the second position to the end of the list. We then concatenate this with a list containing the first element of my_list using the + operator to create a new list shifted_list.

The resulting shifted_list contains the elements of my_list shifted by one position to the left.

  1. Shifting a NumPy Array by Two Positions to the Right:
import numpy as np

my_array = np.array([1, 2, 3, 4, 5])

# Shift the array by two positions to the right
shifted_array = np.concatenate((my_array[-2:], my_array[:-2]))

print(shifted_array)
# Output: [4 5 1 2 3]

In this example, we define a NumPy array my_array containing 5 elements.

We slice the array using my_array[-2:] to select the last two elements of the array and concatenate it with my_array[:-2], which selects all but the last two elements of the array. We use the np.concatenate() function to create a new array shifted_array.

The resulting shifted_array contains the elements of my_array shifted by two positions to the right.

Note that the shift operation can be customized to shift by any number of positions and in any direction depending on your specific needs.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply