• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / How to Rotate a List in Python

How to Rotate a List in Python

February 18, 2022 2 Comments

In Python, the easiest way to rotate items in a list is with the Python list pop(), insert(), and append() functions.

lst = [0,1,2,3]

#rotated backwards (to left)
lst.append(lst.pop(0))
print(lst)

lst= [0,1,2,3]

#rotated forward (to right)
lst.insert(0,lst.pop())
print(lst)

#Output:
[1,2,3,0]
[3,0,1,2]

You can also use the deque() data structure from the Python collections module to rotate a list.

from collections import deque

items = deque([0,1,2,3])

#rotated backwards (to left)
items.rotate(-1)

print(items)

items = deque([0,1,2,3])

#rotated forward (to right)
items.rotate(1)

print(items)

#Output:
deque([1,2,3,0])
deque([3,0,1,2])

You can also use list slicing to rotate a list forward or backwards in Python.

lst= [0,1,2,3]

list_rotated_backwards = lst[1:] + lst[:1]
list_rotated_forward = lst[-1:] + lst[:-1]

print(list_rotated_backwards)
print(list_rotated_forward)

#Output:
[1,2,3,0]
[3,0,1,2]

In Python, lists are one of the most used data structures and allow us to work with collections of data easily. When working with lists, it is useful to be able to change the order of items of a list in an easy way.

With Python, we can easily rotate the items in a list both to the right or the left.

To rotate items to the left, we can remove the first element from the list with pop(), and then append it to the end of the list with the append() function.

To rotate items to the right, we can do the opposite. Rotating to the right involves removing the last element from the list, and then prepending it to the beginning of the list.

Below is an example in Python of how to rotate values in a list using the pop(), append(), and insert() functions.

lst= [0,1,2,3]

#rotated backwards (to left)
lst.append(lst.pop(0))
print(lst)

lst= [0,1,2,3]

#rotated forward (to right)
lst.insert(0,lst.pop())
print(lst)

#Output:
[1,2,3,0]
[3,0,1,2]

If you need to rotate a list multiple times, you can use a loop and apply these operations as many times as needed.

Below is a function which will rotate values in a list multiple times to the left or right depending on the argument values passed.

def rotateList(lst,direction,n):
    if direction == "backwards":
        for i in range(0,n):
            lst.append(lst.pop(0))
    else: 
        for i in range(0,n):
            lst.insert(0,lst.pop())
    return lst

print(rotateList([0,1,2,3,4,5,6],"backwards",2))
print(rotateList([0,1,2,3,4,5,6],"forwards",3))

#Output:
[2, 3, 4, 5, 6, 0, 1]
[4, 5, 6, 0, 1, 2, 3]

Using deque in Python to Rotate a List

Another way that you can rotate a list is with the deque data structure from the Python collections module.

Deque, or doubly ended queue, is most useful if you need to quickly append or pop items from the beginning or end of your data. If you have a large collection of items, you deque can be faster and more efficient than the similar list operations.

To rotate the elements of a list, we can convert it to a deque object and then use the rotate() function.

Below are some examples of how to rotate items in a list with the deque rotate() function.

from collections import deque

items = deque([0,1,2,3])

#rotated backwards (to left)
items.rotate(-1)

print(items)

items = deque([0,1,2,3])

#rotated forward (to right)
items.rotate(1)

print(items)

#Output:
deque([1,2,3,0])
deque([3,0,1,2])

If you want to rotate the items multiple times, you just pass the number of times to rotate().

from collections import deque

items = deque([0,1,2,3,4,5,6])

#rotateed backwards (to left)
items.rotate(-3)

print(items)

items = deque([0,1,2,3,4,5,6])

#rotateed forward (to right)
items.rotate(2)

print(items)

#Output:
deque([3, 4, 5, 6, 0, 1, 2])
deque([5, 6, 0, 1, 2, 3, 4])

Rotating a List in Python with Slicing

You can also rotate the items in a list in Python using list slicing.

To rotate a list backwards, we slice the list from the second element to the end, and then add a slice with only the first element to the end of first slice.

To rotate a list forward, we slice the list from the second to last element to the beginning, and then add a slice with only the last element to the beginning of first slice.

Below is an example of how to rotate a list both backwards and forward with list slicing using Python.

lst= [0,1,2,3]

list_rotated_backwards = lst[1:] + lst[:1]
list_rotated_forward = lst[-1:] + lst[:-1]

print(list_rotated_backwards)
print(list_rotated_forward)

#Output:
[1,2,3,0]
[3,0,1,2]

If you need to rotate a list multiple times, we can define a function which rotates the list a specified number of items.

Below is a function which will rotate the items in a list using slicing multiple times to the left or right depending on the argument values passed.

def rotateList(lst,direction,n):
    if direction == "backwards":
        new_list = lst[n:] + lst[:n]
    else: 
        new_list = lst[-n:] + lst[:-n]
    return new_list

print(rotateList([0,1,2,3,4,5,6],"backwards",2))
print(rotateList([0,1,2,3,4,5,6],"forwards",3))

#Output:
[2, 3, 4, 5, 6, 0, 1]
[4, 5, 6, 0, 1, 2, 3]

Hopefully this article has been useful for you to learn how to rotate lists in Python.

Other Articles You'll Also Like:

  • 1.  Using Python to Convert Integer to String with Leading Zeros
  • 2.  Python sinh – Find Hyperbolic Sine of Number Using math.sinh()
  • 3.  How to Group By Columns and Find Maximum in pandas DataFrame
  • 4.  Python isfinite() Function – Check if Number is Finite with math.isfinite()
  • 5.  Length of Dictionary Python – Get Dictionary Length with len() Function
  • 6.  Python Destroy Object – How to Delete Objects with del Keyword
  • 7.  Python Check if Float is a Whole Number
  • 8.  Drop First n Rows of pandas DataFrame
  • 9.  Check if Line is Empty in Python
  • 10.  Python dirname – Get Directory Name of Path using os.path.dirname()

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Comments

  1. Piotr says

    June 17, 2022 at 5:56 am

    list is a reserver word in python, would propose to use another name for the parameter, also for backwards I think it should be nums[:-k] + nums[-k:]

    Reply
    • Erik says

      June 17, 2022 at 12:44 pm

      Thanks for the comment, I’ve updated the parameter name.

      When I try lst[:-k] + lst[-k:], I’m just getting back the original list.

      lst= [0,1,2,3]
      
      list_rotated_backwards = lst[1:] + lst[:1]
      proposed_method = lst[:-1] + lst[-1:]
      
      print(list_rotated_backwards)
      print(proposed_method)
      
      #Output:
      [1, 2, 3, 0]
      [0, 1, 2, 3]
      Reply

Leave a Reply Cancel reply

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

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy