Select Page

# 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

### 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:

### 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:

## 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.

# 1 Comment

1. Danke dass hat mir wirklich viel weitergeholfen