Q:

Python program to flatten tuple list to string

belongs to collection: Python Tuple Programs

0

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.

All Answers

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

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

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 repeat tuples N times... >>
<< Python program to perform summation of tuple in li...