- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
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.
- Related Articles
- Java program to swap first and last characters of words in a sentence
- Python program to interchange first and last elements in a list
- Python Program to add element to first and last position of linked 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
- Python program to get first and last elements from a tuple
- Golang program to add elements at first and last position of linked list
- Program to swap nodes in a linked list in Python
- 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
- Golang Program to update the last node value in a linked list.
- How to change first and last elements of a list using jQuery?
- Python Program to Sort A List Of Names By Last Name
- Python Program to Print Nth Node from the last of a Linked List
- Golang Program to update the first node value in a linked list.