Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to convert tuple into list by adding the given string after every element
When it is required to convert a tuple into a list by adding a given string after every element, list comprehension provides an elegant solution. This technique creates a new list where each original element is followed by the specified string.
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']
How It Works
The list comprehension [element for sub in my_tuple for element in (sub, K)] works as follows:
It iterates through each element
subin the original tupleFor each element, it creates a temporary tuple
(sub, K)containing the original element and the string KIt then iterates through this temporary tuple, adding both the original element and the string to the result list
This effectively places the string K after every original element
Alternative Method Using Loop
You can achieve the same result using a traditional for loop ?
my_tuple = ((15, 16), 71, 42, 99)
K = "Pyt"
my_result = []
for element in my_tuple:
my_result.append(element)
my_result.append(K)
print("The result is :")
print(my_result)
The result is : [(15, 16), 'Pyt', 71, 'Pyt', 42, 'Pyt', 99, 'Pyt']
Conclusion
List comprehension provides a concise way to convert a tuple into a list while inserting a string after each element. The nested comprehension iterates through elements and creates pairs, effectively doubling the list size with alternating original elements and the specified string.
