Python program to convert tuple into list by adding the given string after every element


When it is required to convert tuple into list by adding the given string after every element, the list comprehension is used.

Example

Below is a demonstration of the same −

my_tuple = ((15, 16), (71), 42, 99)

print("The tuple is :")
print(my_tuple)

K = "Pyt"
print("The value of K is :")
print(K)

my_result = [element for sub in my_tuple for element in (sub, K)]

print("The result is :")
print(my_result)

Output

The tuple is :
((15, 16), 71, 42, 99)
The value of K is :
Pyt
The result is :
[(15, 16), 'Pyt', 71, 'Pyt', 42, 'Pyt', 99, 'Pyt']

Explanation

  • A tuple of tuple of integers is defined and is displayed on the console.

  • A value for K is defined and is displayed on the console.

  • A list comprehension is used to iterate over the elements and the ‘in’ operator is used to check if element is same as the K value specified.

  • If yes, this is converted to a list, and is assigned to a variable

  • This is the output that is displayed on the console.

Updated on: 08-Sep-2021

140 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements