Q:

Python program to flatten tuple of lists to a tuple

belongs to collection: Python Tuple Programs

0

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)

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to flatten tuples of a list is by using the sum() method with empty lust which will return all elements of the tuple as individual values in the list. Then we will convert it into a tuple.

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:

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)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to change the sign of elements of t... >>
<< Python program to concatenate maximum tuples...