The Wayback Machine - https://web.archive.org/web/20241001011820/https://www.geeksforgeeks.org/python-program-to-interchange-first-and-last-elements-in-a-list/
Open In App

Python program to interchange first and last elements in a list

Last Updated : 25 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a list, write a Python program to swap the first and last element of the list using Python.

Examples: The last element of the list can be referred to as a list[-1]. Therefore, we can simply swap list[0] with list[-1].

Python
# Initialize a list
my_list = [1, 2, 3, 4, 5]

# Interchange first and last elements
my_list[0], my_list[-1] = my_list[-1], my_list[0]

# Print the modified list
print("List after swapping first and last elements:", my_list)

Output

List after swapping first and last elements: [5, 2, 3, 4, 1]

Interchange first and last elements using Temporary Value

Find the length of the list and simply swap the first element with (n-1)th element.

Python
# Swap function
def swapList(newList):
    size = len(newList)
    
    # Swapping 
    temp = newList[0]
    newList[0] = newList[size - 1]
    newList[size - 1] = temp
    
    return newList
    
# Driver code
newList = [12, 35, 9, 56, 24]

print(swapList(newList))

Output
[24, 35, 9, 56, 12]

Swapping first and last items in a list using tuple variable

Swap the first and last element is using tuple variable. Store the first and last element as a pair in a tuple variable, say get, and unpack those elements with first and last element in that list. Now, the First and last values in that list are swapped. 

Python
# Swap function
def swapList(list):
    
    # Storing the first and last element 
    # as a pair in a tuple variable get
    get = list[-1], list[0]
    
    # unpacking those elements
    list[0], list[-1] = get
    
    return list
    
# Driver code
newList = [12, 35, 9, 56, 24]
print(swapList(newList))

Output
[24, 35, 9, 56, 12]

Swap first and last values in a list in Python using * operand

This operand proposes a change to iterable unpacking syntax, allowing to specify a “catch-all” name which will be assigned a list of all items not assigned to a “regular” name. 

Python
list = [1, 2, 3, 4]

a, *b, c = list

print(a)
print(b)
print(c)

Output
1
[2, 3]
4

Now let’s see the implementation of above approach: 

Python
# Swap function
def swapList(list):
    
    start, *middle, end = list
    list = [end, *middle, start]
    
    return list
    
# Driver code
newList = [12, 35, 9, 56, 24]

print(swapList(newList))

Output
[24, 35, 9, 56, 12]

Swap first and last values in a list in Python using Slicing

In this approach, we first check if the list has at least 2 elements. If the list has at least 2 elements, we swap the first and last elements using Python slicing by assigning the value of the last element to the first element and the value of the first element to the last element. We then slice the list from the second element to the second-to-last element and concatenate it with a list containing the first element and the last element in their new positions.

Python
def swap_first_last_3(lst):
    # Check if list has at least 2 elements
    if len(lst) >= 2:
        # Swap the first and last elements using slicing
        lst = lst[-1:] + lst[1:-1] + lst[:1]
    return lst

# Initializing the input
inp=[12, 35, 9, 56, 24]

# Printing the original input
print("The original input is:",inp)

result=swap_first_last_3(inp)

# Printing the result
print("The output after swap first and last is:",result)

Output
The original input is: [12, 35, 9, 56, 24]
The output after swap first and last is: [24, 35, 9, 56, 12]

Time Complexity: O(1)
Space Complexity: O(1)

FAQs

How do you find the first and last items in a list Python?

To find the first and last items in a list in Python, you can use indexing. The first item in a list has index 0, and the last item has index -1. Here’s how you can do it:

# Sample list
my_list = [1, 2, 3, 4, 5]
# Find the first item
first_item = my_list[0]
# Find the last item
last_item = my_list[-1]

How to switch the first and last characters in a string Python?

To switch the first and last characters in a string in Python, you can use string slicing and concatenation. Here’s how you can do it:

# Sample string
my_string = “”hello””
# Switch first and last characters
new_string = my_string[-1] + my_string[1:-1] + my_string[0]

How to shift elements in a list in Python?

To shift elements in a list in Python, you can use slicing and concatenation. Here’s how you can shift elements to the left by one position:

# Sample list
my_list = [1, 2, 3, 4, 5]
# Shift elements to the left by one position
shifted_list = my_list[1:] + [my_list[0]]

How to move an element to the end of a list in Python?

To move an element to the end of a list in Python, you can use list methods such as pop() and append(). Here’s how you can move the first element to the end of the list:

# Sample list
my_list = [1, 2, 3, 4, 5]# Move the first element to the end
my_list.append(my_list.pop(0))

How to swap characters in a list?

To swap characters in a string in Python, you can convert the string to a list, perform the swap, and then convert the list back to a string. Here’s how you can swap the first and last characters:

# Sample string
my_string = “hello”# Convert string to list
my_list = list(my_string)# Swap first and last characters
my_list[0], my_list[-1] = my_list[-1], my_list[0]# Convert list back to string
new_string = “”.join(my_list)



Previous Article
Next Article

Similar Reads

Python Program to Interchange elements of first and last rows in matrix
Given a 4 x 4 matrix, we have to interchange the elements of first and last row and show the resulting matrix. Examples : Input : 3 4 5 0 2 6 1 2 2 7 1 2 2 1 1 2 Output : 2 1 1 2 2 6 1 2 2 7 1 2 3 4 5 0 Input : 9 7 5 1 2 3 4 1 5 6 6 5 1 2 3 1 Output : 1 2 3 1 2 3 4 1 5 6 6 5 9 7 5 1 Method 1:The approach is very simple, we can simply swap the eleme
4 min read
Python Program to Interchange Diagonals of Matrix
Given a square matrix of order n*n, you have to interchange the elements of both diagonals. Examples : Input : matrix[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9} Output : matrix[][] = {3, 2, 1, 4, 5, 6, 9, 8, 7} Input : matrix[][] = {4, 2, 3, 1, 5, 7, 6, 8, 9, 11, 10, 12, 16, 14, 15, 13} Output : matrix[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 11, 14, 1
2 min read
Python | Merge first and last elements separately in a list
Given a list of lists, where each sublist consists of only two elements, write a Python program to merge the first and last element of each sublist separately and finally, output a list of two sub-lists, one containing all first elements and other containing all last elements. Examples: Input : [['x', 'y'], ['a', 'b'], ['m', 'n']] Output : [['x', '
2 min read
Python - Find the distance between first and last even elements in a List
Given a List, write a Python program to find the span of even elements in list, i.e distance between first and last occurrence of even element. Examples: Input : test_list = [1, 3, 7, 4, 7, 2, 9, 1, 10, 11] Output : 5 Explanation : Even elements begin at 4 and end at 10, spanning 5 indices. Input : test_list = [1, 3, 7, 4, 7, 2, 9, 1, 1, 11] Output
5 min read
Get first and last elements of a list in Python
Sometimes, there might be a need to get the range between which a number lies in the list, for such applications we require to get the first and last element of the list. Let's discuss certain ways to get the first and last element of the Python list. Get the first elements of a list using indexUsing the list indices inside the master list can perf
6 min read
How to get the first and last elements of Deque in Python?
Deque is a Double Ended Queue which is implemented using the collections module in Python. Let us see how can we get the first and the last value in a Deque. Method 1: Accessing the elements by their index. The deque data structure from the collections module does not have a peek method, but similar results can be achieved by fetching the elements
2 min read
How toGet First and Last Elements from a Tuple in Python
Tuples are immutable sequences in Python that can store a collection of items. Often, we might need to the retrieve the first and last elements from the tuple. In this article, we'll explore how to achieve this using the various methods in Python. Get First and Last Elements from a Tuple Using IndexingWe can use indexing to access the first and las
2 min read
Python Program to swap the First and the Last Character of a string
Given a String. The task is to swap the first and the last character of the string. Examples: Input: GeeksForGeeks Output: seeksForGeekG Input: Python Output: nythoP Python string is immutable which means we cannot modify it directly. But Python has string slicing which makes it very easier to perform string operations and make modifications. Follo
2 min read
Python Program to Find Sum of First and Last Digit
Given a positive integer N(at least contain two digits). The task is to write a Python program to add the first and last digits of the given number N. Examples: Input: N = 1247 Output: 8 Explanation: First digit is 1 and Last digit is 7. So, addition of these two (1 + 7) is equal to 8.Input: N = 73 Output: 10Method 1: String implementationTake inpu
5 min read
Python program to capitalize the first and last character of each word in a string
Given the string, the task is to capitalize the first and last character of each word in a string. Examples: Input: hello world Output: HellO WorlDInput: welcome to geeksforgeeksOutput: WelcomE TO GeeksforgeekSApproach:1 Access the last element using indexing.Capitalize the first word using the title() method.Then join each word using join() method
2 min read
Python | Shift last element to first position in list
The cyclic rotations have been discussed in the earlier articles. In Python, sometimes we just require a specific task, a part of rotation i.e. shift the last element to first element in the list. This has the application in day-day programming in certain utilities. Let's discuss certain ways in which this can be achieved. Shift Last Element to Fir
6 min read
Python - Group first elements by second elements in Tuple list
Given List of tuples, group 1st elements on basis of 2nd elements. Input : test_list = [(6, 5), (2, 7), (2, 5), (8, 7), (3, 7)] Output : {5: [6, 2], 7: [2, 8, 3]} Explanation : 5 occurs along with 6 and 2 in tuple list, hence grouping. Input : test_list = [(6, 5), (2, 7), (2, 5), (8, 7)] Output : {5: [6, 2], 7: [2, 8]} Explanation : 5 occurs along
5 min read
Python | Replace elements in second list with index of same element in first list
Given two lists of strings, where first list contains all elements of second list, the task is to replace every element in second list with index of elements in first list. Method #1: Using Iteration C/C++ Code # Python code to replace every element # in second list with index of first element. # List Initialization Input1 = ['cut', 'god', 'pass']
5 min read
Python | Subtract two list elements if element in first list is greater
Given two list, If element in first list in greater than element in second list, then subtract it, else return the element of first list only.Examples: Input: l1 = [10, 20, 30, 40, 50, 60] l2 = [60, 50, 40, 30, 20, 10] Output: [10, 20, 30, 10, 30, 50] Input: l1 = [15, 9, 10, 56, 23, 78, 5, 4, 9] l2 = [9, 4, 5, 36, 47, 26, 10, 45, 87] Output: [6, 5,
5 min read
Select first or last N rows in a Dataframe using head() and tail() method in Python-Pandas
Let’s discuss how to select top or bottom N number of rows from a Dataframe using head() & tail() methods. 1) Select first N Rows from a Dataframe using head() method of Pandas DataFrame : Pandas head() method is used to return top n (5 by default) rows of a data frame or series Syntax: Dataframe.head(n). Parameters: (optional) n is integer value,
2 min read
Python - Create a string made of the first and last two characters from a given string
Here we are going to see the approach of forming a string made from the first and last 2 characters of a given string. Input: Geeksforgeeks Output: Geks Input: Hi, There Output: Hire Method #1: Using list slicing In this example, we are going to loop through the string and store the length of the string in the count variable and then make the new s
3 min read
Python | Remove last K elements of list
We often come to situations in which we need to decrease the size of the list by truncating the k last elements of the list. This has its application in the day-day programming when sometimes we require getting all the lists of similar size or removing the last few records from a list. Let's discuss a few ways in which this task can be performed. U
6 min read
Python | Get last N elements from given list
Accessing elements in a list has many types and variations. These are an essential part of Python programming and one must have the knowledge to perform the same. This article discusses ways to fetch the last N elements of list. Let's discuss certain solution to perform this task.Method #1 : Using list slicingThis problem can be performed in 1 line
4 min read
Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
The task is to write a Python Program to sort a list of tuples in increasing order by the last element in each tuple. Input: [(1, 3), (3, 2), (2, 1)] Output: [(2, 1), (3, 2), (1, 3)] Explanation: sort tuple based on the last digit of each tuple. Methods #1: Using sorted(). Sorted() method sorts a list and always returns a list with the elements in
7 min read
Python Program to Sort A List Of Names By Last Name
Given a list of names, the task is to write a Python program to sort the list of names by their last name. Examples: Input: ['John Wick', 'Jason Voorhees'] Output: ['Jason Voorhees', 'John Wick'] Explanation: V in Voorhees of Jason Voorhees is less than W in Wick of John Wick. Input: ['Freddy Krueger', 'Keyser Söze','Mohinder Singh Pandher'] Output
3 min read
Python Program For Moving Last Element To Front Of A Given Linked List
Write a function that moves the last element to the front in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4. Algorithm: Traverse the list till the last node. Use two pointers: one to store the address of the last node and the other
3 min read
Python Program For Deleting Last Occurrence Of An Item From Linked List
Using pointers, loop through the whole list and keep track of the node prior to the node containing the last occurrence key using a special pointer. After this just store the next of next of the special pointer, into to next special pointer to remove the required node from the linked list. C/C++ Code # Python program to implement # the above approa
6 min read
Python program to Remove the last element from list
Given a list of numbers or strings, the task is to write a Python program to remove the last element from a list. Example: Input : [12,53,11,76,22,21] Output : [12,53,11,76,22] Input : ["abc","gfg","text","python"] Output : ["abc","gfg","text"] The application of this type of problem in day-day programming when sometimes requires getting all the el
3 min read
Python Program To Find The Sum Of Last N Nodes Of The Given Linked List
Given a linked list and a number n. Find the sum of the last n nodes of the linked list.Constraints: 0 <= n <= number of nodes in the linked list. Examples: Input: 10->6->8->4->12, n = 2 Output: 16 Sum of last two nodes: 12 + 4 = 16 Input: 15->7->9->5->16->14, n = 4 Output: 44Recommended: Please solve it on "PRACTIC
10 min read
Extract First and last N rows from PySpark DataFrame
In this article, we are going to get the extract first N rows and Last N rows from the dataframe using PySpark in Python. To do our task first we will create a sample dataframe. We have to create a spark object with the help of the spark session and give the app name by using getorcreate() method. spark = SparkSession.builder.appName('sparkdf').get
3 min read
Pandas - Convert the first and last character of each word to upper case in a series
In python, if we wish to convert only the first character of every word to uppercase, we can use the capitalize() method. Or we can take just the first character of the string and change it to uppercase using the upper() method. So, to convert the first and last character of each word to upper case in a series we will be using a similar approach. F
2 min read
Python Program that prints elements common at specified index of list elements
Given a list of strings, the task is to write a Python program to extract all characters that are same at a specified index of each element of a list. Illustration: Input : test_list = ["geeks", "weak", "beak", "peek"] Output : ['e', 'k'] Explanation : e and k are at same at an index on all strings.Input : test_list = ["geeks", "weak", "beak", "pee
5 min read
Python program to print elements which are multiples of elements given in a list
Given a list, the task here is to write a Python program to extract elements which are multiple of all elements of custom list. Input : test_list = [4, 24, 8, 10, 12, 23], div_list = [6, 4] Output : [24, 12] Explanation : 24 and 12 divides 6 and 4 both. Input : test_list = [4, 24, 8, 10, 12, 23], div_list = [6, 4, 7] Output : [] Explanation : No el
5 min read
Python Program to get Maximum product of elements of list in a 2D list
Given lists in a list, the task is to write a Python program to find the maximum product of elements of list in a Python 2D list. Examples: Input : [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Output : 504 Explanation:1*2*3 = 6, 4*5*6 = 120, 7*8*9 = 504 Since maximum is 504. Input : [[3, 4], [1, 2, 3], [0, 0]] Output : 12 Explanation:3*4 = 12, 1*2*3 = 6, 0*0
2 min read
Sort the values of first list using second list in Python
Given two lists, sort the values of one list using the second list. Examples: Input : list1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] list2 = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]Output : ['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g'] Input : list1 = ["g", "e", "e", "k", "s", "f", "o", "r", "g", "e", "e", "k", "s"] list2 = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]O
6 min read