Program to flatten tuple of list to tuple using Python

by | Jul 6, 2021 | Python Programs

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.

Author

1 Comment

  1. Tim

    Danke dass hat mir wirklich viel weitergeholfen

    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

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