Home »
Python »
Python Programs
Python program to flatten tuple of lists to a tuple
Here, we have a tuple of lists and we need to flatten it to a tuple in Python programming language.
By Shivang Yadav Last updated : December 12, 2023
Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.
Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.
Example:
tuple = ("python", "includehelp", 43, 54.23)
List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of ordered set of values enclosed in square brackets [].
Example:
list = [3 ,1, 5, 7]
Tuple of lists is a combination of nested collections. In which multiple lists are enclosed inside a tuple.
Example:
listTup = ([4, 1, 8], [9, 0])
Flattening a tuple of list is converting the tuple of lists to a simple tuple containing all individual elements of the lists of the tuple.
Flatten tuple of lists to a tuple
To flatten a tuple of list to a tuple we need to put all the elements of the list in a main tuple container.
Input:
([4, 9, 1], [5 ,6])
Output:
(4, 9, 1, 5, 6)
For performing this task python provides some methods. Let's explore them,
Method 1: Using tuple() and sum() methods
One method to flatten tuples of a list is by using the sum() method with empty list which will return all elements of the tuple as individual values in the list. Then we will convert it into a tuple using the tuple() method.
Program
# Python program to flatten a tuple of list to a tuple
# creating the tuple of list and printing values
listTup = ([4, 9, 1], [5 ,6])
print("The tuple of list : " + str(listTup))
# flattening of tuple of list
flatTup = tuple(sum(listTup, []))
# Printing the flattened tuple
print("Tuple after flattening : " + str(flatTup))
Output:
The tuple of list : ([4, 9, 1], [5, 6])
Tuple after flattening : (4, 9, 1, 5, 6)
Method 2: Using chain.from_iterable() method
Another method is using a method from Python's itertools library. The chain.from_iterable() method is used to extract single values from the tuple of a list and store them in a collection. Then we will convert this collection to tuple.
Program
# Python program to flatten a tuple of list to a tuple
from itertools import chain
# creating the tuple of list and printing values
listTup = ([4, 9, 1], [5 ,6])
print("The tuple of list : " + str(listTup))
# flattening of tuple of list
flatTup = tuple(chain.from_iterable(listTup))
# Printing the flattened tuple
print("Tuple after flattening : " + str(flatTup))
Output:
The tuple of list : ([4, 9, 1], [5, 6])
Tuple after flattening : (4, 9, 1, 5, 6)
Python Tuple Programs »