Python | Shift last element to first position in list
The cyclic rotations have been discussed in the earlier articles. But sometimes, we just require a specific task, a part of rotation i.e shift last element to first element in list. This has the application in day-day programming in certain utilities. Let’s discuss certain ways in which this can be achieved.
Method #1 : Using list slicing and “+” operator
The combination of these functions can be used to perform the task of a single shift in list. The last element is added to the rest of the list to achieve this task using slicing.
# Python3 code to demonstrate # shift last element to first # using list slicing and "+" operator # initializing list test_list = [1, 4, 5, 6, 7, 8, 9, 12] # printing the original list print ("The original list is : " + str(test_list)) # using list slicing and "+" operator # shift last element to first test_list = test_list[-1:] + test_list[:-1] # printing result print ("The list after shift is : " + str(test_list)) |
The original list is : [1, 4, 5, 6, 7, 8, 9, 12] The list after shift is : [12, 1, 4, 5, 6, 7, 8, 9]
Method #2 : Using insert() + pop()
This functionality can also be achieved using the inbuilt functions of python viz. insert() and pop(). The pop function returns the last element and that is inserted at front using the insert function.
# Python3 code to demonstrate # shift last element to first # using insert() + pop() # initializing list test_list = [1, 4, 5, 6, 7, 8, 9, 12] # printing the original list print ("The original list is : " + str(test_list)) # using insert() + pop() # shift last element to first test_list.insert(0, test_list.pop()) # printing result print ("The list after shift is : " + str(test_list)) |
The original list is : [1, 4, 5, 6, 7, 8, 9, 12] The list after shift is : [12, 1, 4, 5, 6, 7, 8, 9]
Recommended Posts:
- Python | Maximum and minimum element's position in a list
- Python | Position Summation in List of Tuples
- Python | Replace elements in second list with index of same element in first list
- Python | Slicing list from Kth element to last element
- Python | Three element sum in list
- Python | How to get the last element of list
- Python | Move element to end of the list
- Python | Element repetition in list
- Python | Operate on every Kth element of list
- Python | Add the element in the list with help of indexing
- Python | Last occurrence of some element in a list
- Python | Insert after every Nth element in a list
- Python | Removing first element of list
- Python | Operation to each element in list
- Python | Accessing nth element from tuples in list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



