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

PythonServer Side ProgrammingProgramming

When it is required to convert a tuple into a list, by the addition of a string after every element, list comprehension is used.

Below is a demonstration of the same −

Example

 Live Demo

my_tup = (56, 78, 91, 32, 45, 11, 23)

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

K = "Hi"

my_result = [elem for sub in my_tup for elem in (sub, K)]

print("The tuple after conversion with K is : ")
print(my_result)

Output

The tuple is :
(56, 78, 91, 32, 45, 11, 23)
The tuple after conversion with K is :
[56, 'Hi', 78, 'Hi', 91, 'Hi', 32, 'Hi', 45, 'Hi', 11, 'Hi', 23, 'Hi']

Explanation

  • A tuple is defined, and is displayed on the console.

  • The value of K, a string, is defined.

  • The list comprehension is used to iterate through the tuple elements, and convert it into a list.

  • This is assigned to a variable.

  • This is displayed as output on the console.

raja
Published on 15-Apr-2021 13:18:55
Advertisements