Q:

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

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of an ordered set of values enclosed in square brackets [].

Example:

list = [3 ,1,  5, 7]

Converting Tuple to List in Python

In real-life programming, there are a lot of times when we need to convert one collection to another. Also, adding or subtracting values from the collection while conversion.

We will see a similar implementation where we will be converting tuple to list and adding new elements and inserting the string between them.

Python provides multiple methods to perform the task.

All Answers

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

Method 1:

A method to solve the problem is by using built-in methods named from_iterable() from the chain library. We will loop over the tuple and then add values to create a list.

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

from itertools import chain

# Initialising and printing the tuple
tup = (19, 54, 7, 10)
print("The initial tuple is ", tup)
addString = "Python"

# Converting the List to tuple 
convList = list(chain.from_iterable((value, addString) for value in tup))

# Printing result
print("List with string added : ", convList)

Output:

The initial tuple is  (19, 54, 7, 10)
List with string added :  [19, 'Python', 54, 'Python', 7, 'Python', 10, 'Python']

Method 2:

Another method to solve the problem is by using list comprehension techniques. It can make the solution more effective and also use of imported functions is not required.

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

# Initialising and printing the tuple
tup = (19, 54, 7, 10)
print("The initial tuple is ", tup)
addString = "Python"

# Converting the List to tuple 
convList = [element for value in tup for element in (value, addString)]

# Printing result
print("List with string added : ", convList)

Output:

The initial tuple is  (19, 54, 7, 10)
List with string added :  [19, 'Python', 54, 'Python', 7, 'Python', 10, 'Python']

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 sort tuples by their maximum ele... >>
<< Python program to convert tuple matrix to tuple li...