Python program to flatten tuple list to string

In this problem, we are given a list of tuples consisting of integer values wrapped as strings. Our task is to create a Python program to flatten the tuple list to string.
Submitted by Shivang Yadav, on January 13, 2022

Some fields where python is implemented require conversion of collection from one type to another which might sometimes involve flattening or nesting too. And python provides methods that are able to perform this task. Here, we will see a Python program to flatten Tuple List to String.

Before going further with the problem, let's recap some basic topics that will help in understanding the solution.

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)

Flatten tuple list to string

We are given a list of tuples consisting of integer elements wrapped as strings. We need to create a Python program to flatten the tuple list to String.

We will be creating a program that will flatten the tuple and create a string with the flattened elements. In Python, we have multiple methods and ways to perform this task.

Method 1:

One method to solve the problem is by iterating over each element of the tuple list and creating a new string with all elements joined using the join() method. The iteration is done using list comprehension.

# Python program to flatten tuple list 
# to string using join() 

# Initializing and printing 
# list of tuples
tupList = [('5', '6') ,('1', '8')]
print("The elements of Tuple list are " + str(tupList))

# Flattening Tuple List to String
flatStr = ' '.join([idx for tup in tupList for idx in tup])
print("String consisting of elements of Tuple : " + flatStr)

Output:

The elements of Tuple list are [('5', '6'), ('1', '8')]
String consisting of elements of Tuple : 5 6 1 8

Method 2:

We can use the chain() method from itertools library instead of the list comprehension to iterate elements for concatenation.

# Python Program to flatten Tuple Lists 
# to String using join() and chain() 
# methods

import itertools

# Initializing and printing list of tuples
tupList = [('5', '6') ,('1', '8')]
print("The elements of Tuple list are " + str(tupList))

# Flattening Tuple List to String
flatStr = ' '.join(itertools.chain(*tupList))
print("String consisting of elements of Tuple : " + flatStr)

Output:

The elements of Tuple list are [('5', '6'), ('1', '8')]
String consisting of elements of Tuple : 5 6 1 8

Python Tuple Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.