- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 – Extend consecutive tuples
When it is required to extend consecutive tuples, a simple iteration is used.
Example
Below is a demonstration of the same −
my_list = [(13, 526, 73), (23, 67, 0, 72, 24, 13), (94, 42), (11, 62, 23, 12), (93, ), (83, 61)] print("The list is :") print(my_list) my_list.sort(reverse=True) print("The list after sorting in reverse is :") print(my_list) my_result = [] for index in range(len(my_list) - 1): my_result.append(my_list[index] + my_list[index + 1]) print("The result is :") print(my_result)
Output
The list is : [(13, 526, 73), (23, 67, 0, 72, 24, 13), (94, 42), (11, 62, 23, 12), (93,), (83, 61)] The list after sorting in reverse is : [(94, 42), (93,), (83, 61), (23, 67, 0, 72, 24, 13), (13, 526, 73), (11, 62, 23, 12)] The result is : [(94, 42, 93), (93, 83, 61), (83, 61, 23, 67, 0, 72, 24, 13), (23, 67, 0, 72, 24, 13, 13, 526, 73), (13, 526, 73, 11, 62, 23, 12)]
Explanation
A list of tuples is defined and is displayed on the console.
It is sorted in reverse using ‘sorted’ method and displayed on the console.
An empty list is created.
The list is iterated over, consecutive elements are added and appended to the empty list.
This is the output that is displayed on the console.
Advertisements