Given list of tuples, join consecutive tuples.
Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)] Output : [(3, 5, 6, 7, 3, 2, 4, 3), (3, 2, 4, 3, 9, 4), (9, 4, 2, 3, 2)] Explanation : Elements joined with their consecutive tuples. Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3)] Output : [(3, 5, 6, 7, 3, 2, 4, 3)] Explanation : Elements joined with their consecutive tuples.
Method #1 : Using loop
This is brute way in which this task can be performed. In this, we perform task of joining consecution by access inside loop.
Python3
test_list = [( 3 , 5 , 6 , 7 ), ( 3 , 2 , 4 , 3 ), ( 9 , 4 ), ( 2 , 3 , 2 ), ( 3 , ), ( 3 , 6 )]
print ( "The original list is : " + str (test_list))
res = []
for idx in range ( len (test_list) - 1 ):
res.append(test_list[idx] + test_list[idx + 1 ])
print ( "Joined tuples : " + str (res))
|
Output
The original list is : [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2), (3, ), (3, 6)]
Joined tuples : [(3, 5, 6, 7, 3, 2, 4, 3), (3, 2, 4, 3, 9, 4), (9, 4, 2, 3, 2), (2, 3, 2, 3), (3, 3, 6)]
Time Complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.
Method #2 : Using zip() + list comprehension
In this, we construct consecutive list using zip() and slicing and then form pairs accordingly.
Python3
test_list = [( 3 , 5 , 6 , 7 ), ( 3 , 2 , 4 , 3 ), ( 9 , 4 ), ( 2 , 3 , 2 ), ( 3 , ), ( 3 , 6 )]
print ( "The original list is : " + str (test_list))
res = [a + b for a, b in zip (test_list, test_list[ 1 :])]
print ( "Joined tuples : " + str (res))
|
Output
The original list is : [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2), (3, ), (3, 6)]
Joined tuples : [(3, 5, 6, 7, 3, 2, 4, 3), (3, 2, 4, 3, 9, 4), (9, 4, 2, 3, 2), (2, 3, 2, 3), (3, 3, 6)]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
10 Mar, 2023
Like Article
Save Article