Sometimes, while working with Python Tuples, we can have a problem in which we need to perform concatenation of single values tuples, to make them into groups of bigger size. This kind of problem can occur in web development and day-day programming. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [(3, ), (6, ), (8, ), (2, ), (9, ), (4, ), (7, ), (1, )], K = 4
Output : [(3, 6, 8, 2), (9, 4, 7, 1)]
Input : test_list = [(3, ), (6, ), (8, ), (2, ), (9, ), (4, ), (7, ), (1, )], K = 2
Output : [(3, 6), (8, 2), (9, 4), (7, 1)]
Method #1 : Using
zip() + list comprehension
The combination of above functions can be used to solve this problem. In this, we perform the task of forming groups using zip() and construction of values using list comprehension. The size of K can only be limited to 2.
The original list is : [(3, ), (6, ), (8, ), (2, ), (9, ), (4, )] Concatenated tuples : [(3, 6), (8, 2), (9, 4)]
Method #2 : Using
zip_longest() + chain.from_iterables()
The combination of above functions can be used to solve this problem. In this, we perfrom the task of concatenation using zip_longest() and chain.from_iterables() is used to flatten tuples to list elements before concatenation.
The original list is : [(3, ), (6, ), (8, ), (2, ), (9, ), (4, )] Concatenated tuples : [(3, 6, 8), (2, 9, 4)]
- Python - Convert List to Single valued Lists in Tuple
- Python - Unlist Single Valued Dictionary List
- Python - Concatenate Kth element in Tuple List
- Python - Concatenate consecutive elements in Tuple
- Python - Concatenate Rear elements in Tuple List
- Python - Concatenate Tuple to Dictionary Key
- Python - Concatenate Tuple elements by delimiter
- Python | Sort tuple list by Nth element of tuple
- Python | Replace tuple according to Nth tuple element
- Python - Raise elements of tuple as power to another tuple
- Python - Convert Tuple String to Integer Tuple
- Python - Convert Tuple to Tuple Pair
- Python - Flatten tuple of List to tuple
- Python - Convert Tuple Matrix to Tuple List
- Python - Remove K valued key from Nested Dictionary
- Python - Filter unique valued tuples
- Python | Convert tuple records to single string
- Python - Nested List to single value Tuple
- Python | Pandas Series.str.cat() to concatenate string
- Python | Merge, Join and Concatenate DataFrames using Panda
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.