• 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
  • VBA
  • About
You are here: Home / Python / Shift Values in a List Using Python

Shift Values in a List Using Python

February 18, 2022 Leave a Comment

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

list = [0,1,2,3]

#shifted backwards (to left)
list.append(list.pop(0))
print(list)

list = [0,1,2,3]

#shifted forward (to right)
list.insert(0,list.pop())
print(list)

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

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

from collections import deque

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

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

print(items)

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

#shifted 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 shift a list forward or backwards in Python.

list = [0,1,2,3]

list_shifted_backwards = list[1:] + list[:1]
list_shifted_forward = list[-1:] + list[:-1]

print(list_shifted_backwards)
print(list_shifted_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 the items of a list in an easy way.

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

To shift 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 shift items to the right, we can do the opposite. Shifting 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 shift values in a list using the pop(), append(), and insert() functions.

list = [0,1,2,3]

#shifted backwards (to left)
list.append(list.pop(0))
print(list)

list = [0,1,2,3]

#shifted forward (to right)
list.insert(0,list.pop())
print(list)

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

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

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

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

print(shiftList([0,1,2,3,4,5,6],"backwards",2))
print(shiftList([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 Shift a List

Another way that you can shift 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 than the similar list operations.

To shift 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 shift items in a list with the deque rotate() function.

from collections import deque

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

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

print(items)

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

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

print(items)

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

If you want to shift 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])

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

print(items)

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

#shifted 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])

Shifting a List in Python with Slicing

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

To shift 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 shift 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 shift a list both backwards and forward with list slicing using Python.

list = [0,1,2,3]

list_shifted_backwards = list[1:] + list[:1]
list_shifted_forward = list[-1:] + list[:-1]

print(list_shifted_backwards)
print(list_shifted_forward)

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

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

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

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

print(shiftList([0,1,2,3,4,5,6],"backwards",2))
print(shiftList([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 shift lists in Python.

Other Articles You'll Also Like:

  • 1.  Length of Set Python – Get Set Length with Python len() Function
  • 2.  Convert timedelta to Seconds in Python
  • 3.  How to Serialize a Model Object with a List of Lists Using Django Rest Framework in Python
  • 4.  Using Python to Count Odd Numbers in List
  • 5.  Perfect Numbers in Python
  • 6.  Python math.factorial() function – Calculate Factorial of Number
  • 7.  How to Check if String Contains Lowercase Letters in Python
  • 8.  pandas str replace – Replace Text in Dataframe with Regex Patterns
  • 9.  Selenium maximize_window() Function to Maximize Window in Python
  • 10.  Using Python to Find Second Smallest Value in List

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

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

The Programming Expert is a compilation of hundreds of code snippets to help you find solutions to your problems in Python, JavaScript, PHP, HTML, SAS, and more.

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 © 2022 · The Programming Expert · About · Privacy Policy