
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements