Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Extend consecutive tuples
When working with tuples in Python, you may need to extend consecutive tuples by combining each tuple with the next one in the sequence. This creates a new list where each element is the concatenation of two adjacent tuples.
Example
Below is a demonstration of extending consecutive tuples ?
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)
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)]
How It Works
The process involves these key steps:
A list of tuples is defined and displayed on the console.
It is sorted in reverse order using the
sort()method and displayed on the console.An empty list is created to store the results.
The list is iterated over using
range(len(my_list) - 1)to avoid index out of bounds.Consecutive tuples are concatenated using the
+operator and appended to the result list.
Alternative Approach Using List Comprehension
You can achieve the same result more concisely using list comprehension ?
my_list = [(13, 526, 73), (23, 67, 0, 72, 24, 13), (94, 42), (11, 62, 23, 12), (93, ), (83, 61)]
print("The original list is :")
print(my_list)
# Extend consecutive tuples using list comprehension
result = [my_list[i] + my_list[i + 1] for i in range(len(my_list) - 1)]
print("The result is :")
print(result)
The original list is : [(13, 526, 73), (23, 67, 0, 72, 24, 13), (94, 42), (11, 62, 23, 12), (93,), (83, 61)] The result is : [(13, 526, 73, 23, 67, 0, 72, 24, 13), (23, 67, 0, 72, 24, 13, 94, 42), (94, 42, 11, 62, 23, 12), (11, 62, 23, 12, 93), (93, 83, 61)]
Conclusion
Extending consecutive tuples is accomplished by iterating through the list and concatenating each tuple with its next neighbor using the + operator. This technique is useful for combining adjacent data elements in sequence processing tasks.
