- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program to Swap the First and Last Value of a List
When it is required to swap the first and last values of a list using Python, a method can be defined, that uses a simple sorting technique to sort the values.
Below is a demonstration of the same −
def list_swapping(my_list): size_of_list = len(my_list) temp = my_list my_list = my_list[size_of_list - 1] my_list[size_of_list - 1] = temp return my_list my_list = [34, 21, 56, 78, 93, 20, 11, 9] print("The list is :") print(my_list) print("The function to swap the first and last elements is swapped") print(list_swapping(my_list))
The list is : [34, 21, 56, 78, 93, 20, 11, 9] The function to swap the first and last elements is swapped [9, 21, 56, 78, 93, 20, 11, 34]
A method named ‘list_swapping’ is defined.
It takes a list as a parameter.
The first and the last elements of the list are swapped.
The resultant list is returned as output.
Outside the function, a list is defined and displayed on the console.
The method is called bypassing this list as a parameter.
The output is displayed on the console.
- Java program to swap first and last characters of words in a sentence
- Python program to interchange first and last elements in a list
- Get first and last elements of a list in Python
- Java Program to Add Element at First and Last Position of a Linked list
- How to change first and last elements of a list using jQuery?
- Python – Find the distance between first and last even elements in a List
- Java Program to Get First and Last Elements from an Array List
- Program to swap nodes in a linked list in Python
- Golang Program to update the last node value in a linked list.
- Golang Program to update the first node value in a linked list.
- Python Program to Print Nth Node from the last of a Linked List
- Python Pandas - Insert a new index value at the first index from the last
- Program to find a sublist where first and last values are same in Python
- Program to find the K-th last node of a linked list in Python
- Python Program to Form a New String Made of the First 2 and Last 2 characters From a Given String