How to Shift a List in Python?

Estimated read time 1 min read

In Python, you can shift the elements of a list by a specified number of positions using slicing and concatenation.

Here’s an example code that shifts the elements of a list my_list to the left by n positions:

n = 2  # number of positions to shift
my_list = [1, 2, 3, 4, 5]

shifted_list = my_list[n:] + my_list[:n]

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

In this example, we first create a new list shifted_list by concatenating the sublist my_list[n:] (which contains all elements from index n to the end) with the sublist my_list[:n] (which contains all elements from the beginning up to index n-1).

By doing this, we effectively move the first n elements to the end of the list.

Note that the original my_list is not modified by this operation, and the new shifted_list contains the shifted elements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply