
- 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
Reverse each tuple in a list of tuples in Python
When it is required to reverse each tuple in a list of tuples, the negative step slicing can be used.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A list of tuple basically contains tuples enclosed in a list.
In negative slicing, the index is accessed using negative numbers, instead of positive ones.
Below is a demonstration for the same −
Example
def reverse_tuple(my_tuple): return [tup[::-1] for tup in my_tuple] my_list = [(21, 22), (43, 74, 45), (76, 17, 98, 19)] print("The list of tuples is ") print(my_list) print(reverse_tuple(my_list))
Output
The list of tuples is [(21, 22), (43, 74, 45), (76, 17, 98, 19)] [(22, 21), (45, 74, 43), (19, 98, 17, 76)]
Explanation
- A method name 'reverse_tuple' is defined that takes a list of tuple as parameter.
- It iterates through the parameter and uses the '::' operator and negative indexing to return elements up to last index.
- A list of tuple is defined, and is displayed on the console.
- The previously defined user function is called by passing this list of tuples to it.
- This output is displayed on the console.
- Related Articles
- Create a list of tuples from given list having number and its cube in each tuple using Python
- Combinations of sum with tuples in tuple list in Python
- Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple using Python program
- Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
- Python Group by matching second tuple value in list of tuples
- Python program to create a list of tuples from the given list having the number and its cube in each tuple
- How can I subtract tuple of tuples from a tuple in Python?
- Combining tuples in list of tuples in Python
- Remove tuple from list of tuples if not containing any character in Python
- Update each element in tuple list in Python
- Count tuples occurrence in list of tuples in Python
- Remove duplicate tuples from list of tuples in Python
- Update a list of tuples using another list in Python
- Convert list of tuples into list in Python
- Summation of tuples in list in Python

Advertisements