Program to flatten tuple of list to tuple using Python

Introduction

Sometimes while dealing in data science domain, we may come across the scenario where we have to flatten the tuple. Flatten a tuple means converting a matrix in to a simple comma separated value as shown below:

Program to flatten tuple of list to tuple using Python

Program

Approach 1

ip_tuple = ([758, 1, 9, 0], [3])
print("The original tuple :: "+str(ip_tuple))

# Using sum() + tuple()
output = tuple(sum(ip_tuple, []))
print("The flattened tuple : "+str(output))

Output:

Program to flatten tuple of list to tuple using Python Output 1

Approach 2

from itertools import chain
ip_tuple = ([758, 1, 9, 0], [3])
print("The original tuple :: "+str(ip_tuple))


# Using chain.from_iterable()
output = tuple(chain.from_iterable(ip_tuple))


print("The flattened tuple : "+str(output))

Output:

Program to flatten tuple of list to tuple using Python Output 2

Explanation

Approach 1: In our first approach we have used sum() to flatten the tuple list by passing empty list.  And then converted it to tuple using tuple() method.

Approach 2: In second approach we have used chain.from_iterable() to flatten the tuple list and passed input tuple as argument.

One comment

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.