How to shift (rotate) a List in Python [5 Ways]

avatar
Borislav Hadzhiev

Last updated: Apr 11, 2024
6 min

banner

# Table of Contents

  1. How to shift (rotate) a List in Python
  2. How to shift (rotate) a List using append() and pop()
  3. Using the collections.deque class to shift (rotate) a list in Python
  4. How to shift (rotate) a list in Python using numpy.roll

# How to shift (rotate) a List in Python

You can use list slicing to shift (rotate) a list in Python:

  1. Take a slice of the list from index 1 to the end.
  2. Add a slice of the list starting at index 0 and going up to, but not including index 1.
main.py
# โœ… Move the first list item to the back a_list = [1, 2, 3, 4, 5] new_list = a_list[1:] + a_list[:1] print(new_list) # ๐Ÿ‘‰๏ธ [2, 3, 4, 5, 1]

shift rotate list in python

The code for this article is available on GitHub

The example moves the first list item to the back of the list.

If you need to move the last list item to the front of the list, use the following code sample instead.

main.py
# โœ… Move the last list item to the front a_list = [1, 2, 3, 4, 5] new_list = [a_list[-1]] + a_list[:-1] print(new_list) # ๐Ÿ‘‰๏ธ [5, 1, 2, 3, 4]

The example uses list slicing to rotate the list.

The syntax for list slicing is a_list[start:stop:step].

The start index is inclusive and the stop index is exclusive (up to, but not including).

If the start index is omitted, it is considered to be 0, if the stop index is omitted, the slice goes to the end of the list.

Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(a_list) - 1.

The first slice a_list[1:] starts at index 1 and goes to the end of the list.

main.py
a_list = [1, 2, 3, 4, 5] new_list = a_list[1:] + a_list[:1] print(new_list) # ๐Ÿ‘‰๏ธ [2, 3, 4, 5, 1]

The second slice a_list[:1] starts at index 0 and goes up to, but not including index 1.

main.py
a_list = [1, 2, 3, 4, 5] print(a_list[1:]) # ๐Ÿ‘‰๏ธ [1] print(a_list[:1]) # ๐Ÿ‘‰๏ธ [2, 3, 4, 5, 1]

You can also create a reusable function that shifts (rotates) the list based on a supplied index.

main.py
def shift_list(lst, index=1): index = index % len(lst) return lst[index:] + lst[:index] a_list = [1, 2, 3, 4, 5] # ๐Ÿ‘‡๏ธ [2, 3, 4, 5, 1] print(shift_list(a_list, 1)) # ๐Ÿ‘‡๏ธ [2, 3, 4, 5, 1] (without passing index explicitly) print(shift_list(a_list)) # ๐Ÿ‘‡๏ธ [3, 4, 5, 1, 2] print(shift_list(a_list, 2)) # ๐Ÿ‘‡๏ธ [4, 5, 1, 2, 3] print(shift_list(a_list, 3))
The code for this article is available on GitHub

The shift_list function takes a list and optionally an index as parameters and rotates the list.

The use of the % operator is there to account for a shift that is greater than the list's length.

For example, 8 % 5 = 3, so we only shift 3 times which is the same as shifting 8 times.

main.py
def shift_list(lst, index=1): index = index % len(lst) return lst[index:] + lst[:index] a_list = [1, 2, 3, 4, 5] # ๐Ÿ‘‡๏ธ [4, 5, 1, 2, 3] print(shift_list(a_list, 3)) # ๐Ÿ‘‡๏ธ [4, 5, 1, 2, 3] print(shift_list(a_list, 8))
The code for this article is available on GitHub

If an index is not provided, it defaults to 1.

If an index of 1 is used, the first element in the list gets moved to the back (becomes the last element).

Similarly, if an index of 2 is provided, the first two elements of the list get moved to the back.

# How to shift (rotate) a List using append() and pop()

You can also use the list.append() and list.pop() methods to rotate a list in Python.

main.py
# โœ… Move the first list item to the back a_list = [1, 2, 3, 4, 5] a_list.append(a_list.pop(0)) print(a_list) # ๐Ÿ‘‰๏ธ [2, 3, 4, 5, 1]

shift rotate list using append and pop

The code for this article is available on GitHub

The example moves the first list item to the back.

If you need to move the last list item to the front, use the following code sample instead.

main.py
# โœ… Move the last list item to the front a_list = [1, 2, 3, 4, 5] a_list.insert(0, a_list.pop()) print(a_list) # ๐Ÿ‘‰๏ธ [5, 1, 2, 3, 4]

The list.pop() method removes the item at the given position in the list and returns it.

We used the method to remove and return the list item at position 0.

The last step is to use the list.append() method to move the removed list item to the back of the list.

You can use the range class if you need to shift multiple items to the back of the list.

main.py
a_list = [1, 2, 3, 4, 5] for _ in range(2): a_list.append(a_list.pop(0)) print(a_list) # ๐Ÿ‘‰๏ธ [3, 4, 5, 1, 2]

We used a range() of 2 to shift the first 2 items of the list to the back.

main.py
print(list(range(2))) # ๐Ÿ‘‰๏ธ [0, 1] print(list(range(3))) # ๐Ÿ‘‰๏ธ [0, 1, 2]

The range class is commonly used for looping a specific number of times in for loops.

# Using the collections.deque class to shift (rotate) a list in Python

You can also use the collections.deque class to shift (rotate) a list in Python.

main.py
from collections import deque deq = deque([1, 2, 3, 4]) deq.append(5) print(deq) # deque([1, 2, 3, 4, 5]) deq.rotate(1) print(deq) # deque([5, 1, 2, 3, 4]) deq.rotate(-1) print(deq) # deque([1, 2, 3, 4, 5]) deq.rotate(-1) print(deq) # deque([2, 3, 4, 5, 1])
The code for this article is available on GitHub

The deque class returns a deque object that is initialized left-to-right with data from the supplied iterable.

Dequeues are a generalization of stacks and queues and support memory efficient appends and pops from either side.

The deque.rotate() method rotates the deque n steps to the right.

If n is negative, the method rotates the deque object to the left.

When the deque is not empty:

  1. Rotating one step to the right is equivalent to deq.appendleft(deq.pop()).
  2. Rotating one step to the left is equivalent to deq.append(deq.popleft()).

Using the deque.rotate() method is faster than using list slicing, in case you need to optimize for performance.

# How to shift (rotate) a list in Python using numpy.roll

You can also use the numpy.roll() method to rotate a list.

First, make sure you have the numpy module installed.

Open your terminal in your project's root directory and run the following command.

shell
pip install numpy # or pip3 pip3 install numpy

Now import and use the numpy.roll() method as follows.

main.py
import numpy as np arr = np.array([1, 2, 3, 4, 5]) new_array = np.roll(arr, 1) print(new_array) # ๐Ÿ‘‰๏ธ [5 1 2 3 4] new_array = np.roll(arr, -1) print(new_array) # ๐Ÿ‘‰๏ธ [2 3 4 5 1] new_array = np.roll(arr, 2) print(new_array) # ๐Ÿ‘‰๏ธ [4 5 1 2 3]
The code for this article is available on GitHub

The numpy.roll method rolls array elements along a given axis.

The first argument the method takes is the array.

The second argument is the number of places by which elements are shifted.

For example, if you pass 1 as the second argument to the method, the last element gets shifted to the front.

main.py
import numpy as np arr = np.array([1, 2, 3, 4, 5]) new_array = np.roll(arr, 1) print(new_array) # ๐Ÿ‘‰๏ธ [5 1 2 3 4]

If you pass 2 as the second argument, the last 2 elements get shifted to the front.

main.py
import numpy as np arr = np.array([1, 2, 3, 4, 5]) new_array = np.roll(arr, 2) print(new_array) # ๐Ÿ‘‰๏ธ [4 5 1 2 3]

If you pass -1 as the second argument, the first element gets moved to the back of the array.

main.py
import numpy as np arr = np.array([1, 2, 3, 4, 5]) new_array = np.roll(arr, -1) print(new_array) # ๐Ÿ‘‰๏ธ [2 3 4 5 1]
The code for this article is available on GitHub

Similarly, if you pass -2 as the second argument, the first 2 elements get moved to the back.

main.py
import numpy as np arr = np.array([1, 2, 3, 4, 5]) new_array = np.roll(arr, -2) print(new_array) # ๐Ÿ‘‰๏ธ [3 4 5 1 2]

However, it is not necessary to load the entire numpy library just to call the np.roll() method.

Using list slicing as shown in the first subheading should be sufficient for most use cases.

I've also written an article on how to move an item in a list in Python.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev