Open In App

Shift Last Element to First Position in list – Python

Last Updated : 05 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of shifting the last element to the first position in a list in Python involves modifying the order of elements such that the last item of the list is moved to the beginning while the rest of the list remains intact. For example, given a list a = [1, 4, 5, 6, 7, 8, 9, 12], the goal is to shift the last element, 12, to the first position, resulting in the list [12, 1, 4, 5, 6, 7, 8, 9].

Using list slicing

List slicing is one of the most efficient way to shift elements in a list. It allows us to create sublists with minimal overhead and perform the operation concisely in a single line.

Python
a = [1, 4, 5, 6, 7, 8, 9, 12]

a = a[-1:] + a[:-1] 
print (str(a))

Output
[12, 1, 4, 5, 6, 7, 8, 9]

Explanation: a[-1:] + a[:-1] shifts the last element of the list to the front by concatenating the last element (a[-1:]) with the rest of the list (a[:-1]).

Using deque

deque from collections module is specifically optimized for operations at both ends of a list. It’s a great choice for situations where frequent modifications to the ends of the list are required.

Python
from collections import deque
a = [1, 4, 5, 6, 7, 8, 9, 12]

dq = deque(a) # Convert the list into a deque
dq.rotate(1)
a = list(dq)
print(a)

Output
[12, 1, 4, 5, 6, 7, 8, 9]

Explanation: dq.rotate(1) rotates the deque by one position, moving the last element to the front.

Using insert

insert() and pop() methods offer a more manual but still efficient way to shift elements in a list. This method removes the last element using pop() and inserts it at the start using insert().

Python
a = [1, 4, 5, 6, 7, 8, 9, 12]

a.insert(0, a.pop()) 
print(a)

Output
[12, 1, 4, 5, 6, 7, 8, 9]

Explanation:a.insert(0, a.pop()) inserts the popped element 12 at the beginning of the list, shifting the rest of the elements one position to the right.

Using list comprehension

List comprehension provides a concise and elegant way to create a new list, which is useful for performing operations like shifting elements. We can use it to prepend the last element and append the rest of the list.

Python
a = [1, 4, 5, 6, 7, 8, 9, 12]

a = [a[-1]] + [x for x in a[:-1]]
print(a)

Output
[12, 1, 4, 5, 6, 7, 8, 9]

Explanation:[x for x in a[:-1]] creates a new list by iterating over all elements of a except the last one, effectively generating a copy of the list without its last element.



Next Article

Similar Reads