Python list shift

Python List Shift

Python List Shift

In Python, a list is an ordered, mutable collection whose elements can be accessed by index. Sometimes we need to shift elements in a list left or right. This operation is often called “shifting” in other programming languages. This article will explore in detail how to implement list shift operations in Python.

Shifting List Elements Left

First, let’s see how to shift elements in a list left. We can do this using slicing. The steps are as follows:

  1. First, select the range of elements to shift. For example, if we want to shift the first three elements of a list one position to the left, we need to select the elements with indices 0 through 2.
  2. Then, we slice out the selected range of elements and remove the first element.
  3. Finally, we concatenate the sliced range of elements with the rest of the original list.

Here is an example code:

def shift_left(lst, n):
n = n % len(lst)
return lst[n:] + lst[:n]

my_list = [1, 2, 3, 4, 5]
shifted_list = shift_left(my_list, 2)
print(shifted_list)

Running the above code prints:

[3, 4, 5, 1, 2]

In this example, we define a function called shift_left that takes a list and an integer n as arguments, representing the number of positions to shift. We then call this function to shift the list [1, 2, 3, 4, 5] left by two positions, resulting in [3, 4, 5, 1, 2].

Shifting List Elements Right

Similarly, we can shift elements in a list rightward. This operation is accomplished by shifting the reversed range of elements leftward. The steps are as follows:

  1. First, select the range of elements to shift. For example, if we want to shift the last three elements in the list one position to the right, we need to select the elements from indexes -3 to -1.
  2. Then, slice the selected range of elements and remove the last element.
  3. Finally, concatenate the sliced range of elements with the head of the original list.

Here is an example code:

def shift_right(lst, n):
n = n % len(lst)
return lst[-n:] + lst[:-n]

my_list = [1, 2, 3, 4, 5]
shifted_list = shift_right(my_list, 2)
print(shifted_list)

Running the above code prints:

[4, 5, 1, 2, 3]

In this example, we define a function called shift_right that takes a list and an integer n as arguments, representing the number of positions to shift. We then call this function to shift the list [1, 2, 3, 4, 5] right by two positions, resulting in [4, 5, 1, 2, 3].

Summary

Through the above examples, we can see that implementing list shift operations in Python is relatively simple. We can choose to shift left or right as needed, and implement this through slicing and concatenation operations. This operation is very useful when working with circular lists or when circular shifts are required.

Leave a Reply

Your email address will not be published. Required fields are marked *