The Wayback Machine - https://web.archive.org/web/20241009160914/https://www.geeksforgeeks.org/python-program-to-covert-tuple-into-list-by-adding-the-given-string-after-every-element/
Open In App

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

Last Updated : 10 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a Tuple. The task is to convert it to List by adding the given string after every element.

Examples:

Input : test_tup = (5, 6, 7), K = "Gfg" 
Output : [5, 'Gfg', 6, 'Gfg', 7, 'Gfg'] 
Explanation : Added "Gfg" as succeeding element.

Input : test_tup = (5, 6), K = "Gfg" 
Output : [5, 'Gfg', 6, 'Gfg'] 
Explanation : Added "Gfg" as succeeding element.

Method #1: Using list comprehension

In this, we construct a tuple of each element of tuple with a succeeding element and then run a nested loop to flatten each constructed tuple using list comprehension.

Python3




# Python3 code to demonstrate working of
# Convert tuple to List with succeeding element
# Using list comprehension
 
# initializing tuple
test_tup = (5, 6, 7, 4, 9)
 
# printing original tuple
print("The original tuple is : ", test_tup)
 
# initializing K
K = "Gfg"
 
# list comprehension for nested loop for flatten
res = [ele for sub in test_tup for ele in (sub, K)]
 
# printing result
print("Converted Tuple with K : ", res)


Output:

The original tuple is :  (5, 6, 7, 4, 9) 
Converted Tuple with K :  [5, ‘Gfg’, 6, ‘Gfg’, 7, ‘Gfg’, 4, ‘Gfg’, 9, ‘Gfg’]

Time Complexity: O(n) where n is the number of elements in the tuple “test_tup”.  
Auxiliary Space: O(n), where n is the number of elements in the new res list 

Method #2 : Using chain.from_iterable() + list() + generator expression

This is similar to above method, difference is that nested loop is avoided by flattening using chain.from_iterable().

Python3




# Python3 code to demonstrate working of
# Convert tuple to List with succeeding element
# Using chain.from_iterable() + list() + generator expression
from itertools import chain
 
# initializing tuple
test_tup = (5, 6, 7, 4, 9)
 
# printing original tuple
print("The original tuple is : ", test_tup)
 
# initializing K
K = "Gfg"
 
# list comprehension for nested loop for flatten
res = list(chain.from_iterable((ele, K) for ele in test_tup))
 
# printing result
print("Converted Tuple with K : ", res)


Output:

The original tuple is :  (5, 6, 7, 4, 9) 
Converted Tuple with K :  [5, ‘Gfg’, 6, ‘Gfg’, 7, ‘Gfg’, 4, ‘Gfg’, 9, ‘Gfg’]

Time Complexity: The time complexity of this program is O(n), where n is the length of the input tuple test_tup. 

Auxiliary Space: The auxiliary space used by this program is O(n), where n is the length of the input tuple test_tup. 

Method #3 : Using list(),map(),join(),split() methods

Python3




# Python3 code to demonstrate working of
# Convert tuple to List with succeeding element
 
# initializing tuple
test_tup = (5, 6, 7, 4, 9)
 
# printing original tuple
print("The original tuple is : ", test_tup)
 
# initializing K
K = "Gfg"
x = list(map(str, test_tup))
b = "*"+K+"*"
a = b.join(x)
c = a.split("*")
c.append(K)
res = []
for i in c:
    if(i != K):
        res.append(int(i))
    else:
        res.append(i)
# printing result
print("Converted Tuple with K : ", res)


Output :

The original tuple is :  (5, 6, 7, 4, 9) 
Converted Tuple with K :  [5, ‘Gfg’, 6, ‘Gfg’, 7, ‘Gfg’, 4, ‘Gfg’, 9, ‘Gfg’]

Method #4 : Using map() function

Python3




# initializing tuple
test_tup = (5, 6, 7, 4, 9)
 
# printing original tuple
print("The original tuple is : ", test_tup)
 
# initializing K
K = "Gfg"
 
# using map
res = list(map(lambda x: [x, K], test_tup))
res = [j for i in res for j in i]
 
# printing result
print("Converted Tuple with K : ", res)
#This code is contributed by Vinay Pinjala.


Output

The original tuple is :  (5, 6, 7, 4, 9)
Converted Tuple with K :  [5, 'Gfg', 6, 'Gfg', 7, 'Gfg', 4, 'Gfg', 9, 'Gfg']

Time Complexity: O(n)

Auxiliary Space: O(n)

Method#5: Using Recursive method.

Algorithm:

  1. Define a function called tuple_to_list_with_k that takes a tuple and a value k as arguments.
  2. Check if the tuple is empty. If it is, return an empty list.
  3. Otherwise, create a new list by concatenating the first element of the tuple with k, then recursively call the function on the rest of the tuple, and concatenate the result with the new list.
  4. Return the list.
     

Python3




# Python3 code to demonstrate working of
# Convert tuple to List with succeeding element
# Using recursion
def tuple_to_list_with_k(tup, k):
    if not tup:
        return []
    else:
        return [tup[0], k] + tuple_to_list_with_k(tup[1:], k)
 
# initializing tuple
test_tup = (5, 6, 7, 4, 9)
 
# printing original tuple
print("The original tuple is : ", test_tup)
 
# initializing K
K = "Gfg"
 
 
res = tuple_to_list_with_k(test_tup,K)
 
# printing result
print("Converted Tuple with K : ", res)


Output

The original tuple is :  (5, 6, 7, 4, 9)
Converted Tuple with K :  [5, 'Gfg', 6, 'Gfg', 7, 'Gfg', 4, 'Gfg', 9, 'Gfg']

Time complexity: O(n), where n is the length of the input tuple. This is because the function processes each element of the tuple exactly once.

Space complexity: O(n), where n is the length of the input tuple. This is because the function creates a new list to store the output, which can have up to 2n elements (each element of the input tuple is followed by k). Additionally, the function uses the call stack to handle recursive calls, which can have up to n levels of recursion.



Similar Reads

Python program to convert Set into Tuple and Tuple into Set
Let's see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type(). tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value.set(): set method is to convert other type values to set this meth
7 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python - Convert Tuple String to Integer Tuple
Interconversion of data is a popular problem developer generally deal with. One can face a problem to convert tuple string to integer tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task. In this, we perform th
7 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python Program to find tuple indices from other tuple list
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples. Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]Output : [3, 1]Explanation : (3, 4) from search list is found on 3rd index on test_list, hence included in r
8 min read
Python Program to Merge tuple list by overlapping mid tuple
Given two lists that contain tuples as elements, the task is to write a Python program to accommodate tuples from the second list between consecutive tuples from the first list, after considering ranges present between both the consecutive tuples from the first list. Input : test_list1 = [(4, 8), (19, 22), (28, 30), (31, 50)], test_list2 = [(10, 12
11 min read
Python - Convert Tuple to Tuple Pair
Sometimes, while working with Python Tuple records, we can have a problem in which we need to convert Single tuple with 3 elements to pair of dual tuple. This is quite a peculiar problem but can have problems in day-day programming and competitive programming. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ('A'
10 min read
Python - Extract Kth element of every Nth tuple in List
Given list of tuples, extract Kth column element of every Nth tuple. Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)], K = 2, N = 3 Output : [3, 8, 10] Explanation : From 0th, 3rd, and 6th tuple, 2nd elements are 3, 8, 10. Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6,
8 min read
Python | Replace tuple according to Nth tuple element
Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it's application in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + enumerate() This task
8 min read
Python | Convert a list into tuple of lists
We are given a list, the task is to convert the list into tuple of lists. Input: ['Geeks', 'For', 'geeks'] Output: (['Geeks'], ['For'], ['geeks'])Input: ['first', 'second', 'third'] Output: (['first'], ['second'], ['third']) Method #1: Using Comprehension C/C++ Code # Python code to convert a list into tuple of lists # Initialisation of list Input
4 min read
Python | Convert list of tuple into dictionary
Given a list containing all the element and second list of tuple depicting the relation between indices, the task is to output a dictionary showing the relation of every element from the first list to every other element in the list. These type of problems are often encountered in Coding competition. Below are some ways to achieve the above task. I
8 min read
Python | Convert a List into a Tuple
Given a list, write a Python program to convert the given list into a Python tuple. Example Convert a list into a tuple using tuple(list_name). Typecasting to a tuple can be done by simply using tuple(list_name). [GFGTABS] Python # Driver function lis = [1, 2, 3, 4] print(type(lis)) # list into a tuple print(type(tuple(lis))) [/GFGTABS]Output<cl
5 min read
Python | Convert mixed data types tuple list to string list
Sometimes, while working with records, we can have a problem in which we need to perform type conversion of all records into a specific format to string. This kind of problem can occur in many domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + tuple() + str() + generator expression The co
5 min read
Python | Adding N to Kth tuple element
Many times, while working with records, we can have a problem in which we need to change the value of tuple elements. This is a common problem while working with tuples. Let's discuss certain ways in which N can be added to Kth element of tuple in list. Method #1 : Using loop Using loops this task can be performed. In this, we just iterate the list
3 min read
Python Program to Convert Tuple Value List to List of Tuples
Given a dictionary with values as a tuple list, convert it to a key-mapped list of tuples. Input : test_dict = {'Gfg' : [(5, ), (6, )], 'is' : [(5, )], 'best' :[(7, )]} Output : [('Gfg', 5), ('Gfg', 6), ('is', 5), ('best', 7)] Explanation : Keys grouped with values.Convert Tuple Value List to List of Tuples Using loop + * operator + items() This is
8 min read
Python program to convert a list of strings with a delimiter to a list of tuple
Given a List containing strings with a particular delimiter. The task is to remove the delimiter and convert the string to the list of tuple. Examples: Input : test_list = ["1-2", "3-4-8-9"], K = "-" Output : [(1, 2), (3, 4, 8, 9)] Explanation : After splitting, 1-2 => (1, 2). Input : test_list = ["1*2", "3*4*8*9"], K = "*" Output : [(1, 2), (3,
7 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python - Adding Tuple to List and vice - versa
Sometimes, while working with Python containers, we can have a problem in which we need to perform addition of one container with another. This kind of problem can have occurrence in many data domains across Computer Science and Programming. Let's discuss certain ways in which this task can be performed. Method 1 : Using += operator [list + tuple]
5 min read
Python | Merge list of tuple into list by joining the strings
Sometimes, we are required to convert list of tuples into a list by joining two element of tuple by a special character. This is usually with the cases with character to string conversion. This type of task is usually required in the development domain to merge the names into one element. Let’s discuss certain ways in which this can be performed. L
6 min read
Python | Convert list to indexed tuple list
Sometimes, while working with Python lists, we can have a problem in which we need to convert a list to tuple. This kind of problem have been dealt with before. But sometimes, we have it's variation in which we need to assign the index of the element along with element as a tuple. Let's discuss certain ways in which this task can be performed. Meth
3 min read
Python | Convert Integral list to tuple list
Sometimes, while working with data, we can have a problem in which we need to perform type of interconversions of data. There can be a problem in which we may need to convert integral list elements to single element tuples. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension List comprehension can be
3 min read
Convert List of Dictionary to Tuple list Python
Given a list of dictionaries, write a Python code to convert the list of dictionaries into a list of tuples.Examples: Input: [{'a':[1, 2, 3], 'b':[4, 5, 6]}, {'c':[7, 8, 9], 'd':[10, 11, 12]}] Output: [('b', 4, 5, 6), ('a', 1, 2, 3), ('d', 10, 11, 12), ('c', 7, 8, 9)] Below are various methods to convert a list of dictionaries to a list of Python t
5 min read
Python program to create a list of tuples from given list having number and its cube in each tuple
Given a list of numbers of list, write a Python program to create a list of tuples having first element as the number and second element as the cube of the number. Example: Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)] Input: list = [9, 5, 6] Output: [(9, 729), (5, 125), (6, 216)] Method #1 : Using pow() function.We can use list compreh
5 min read
Python | Convert String to tuple list
Sometimes, while working with Python strings, we can have a problem in which we receive a tuple, list in the comma-separated string format, and have to convert to the tuple list. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + split() + replace() This is a brute force method to perform this task. In this, we
5 min read
Python - Insert after every Nth element in a list
Sometimes we need to perform a single insertion in python, this can be easily done with the help of the insert function. But sometimes, we require to insert in a repeated manner after every n numbers, for that there can be numerous shorthands that can be quite handy. Lets discuss certain ways in which this can be done. Method #1 : Using join() + en
7 min read
Python | Program to convert a tuple to a string
Given a tuple of characters, Write a python program to convert the tuple into a string. Examples: Input : ('a', 'b', 'c', 'd', 'e') Output : abcde Input : ('g', 'e', 'e', 'k', 's') Output : geeks Approach 1: using simple for loop Create an empty string and using a for loop iterate through the elements of the tuple and keep on adding each element to
4 min read
Python - Convert tuple list to dictionary with key from a given start value
Given a tuple list, the following article focuses on how to convert it to a dictionary, with keys starting from a specified start value. This start value is only to give a head start, next keys will increment the value of their previous keys. Input : test_list = [(4, 5), (1, 3), (9, 4), (8, 2), (10, 1)], start = 4 Output : {4: (4, 5), 5: (1, 3), 6:
4 min read
Python - Raise elements of tuple as power to another tuple
Sometimes, while working with records, we can have a problem in which we may need to perform exponentiation, i.e power of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1: Using zip() + generator expression The combination of above functions can be used to perform this
8 min read
Tuple within a Tuple in Python
In the realm of Python programming, tuples offer a flexible solution for organizing data effectively. By allowing the inclusion of other tuples within them, tuples further enhance their capabilities. In this article, we will see how we can use tuple within a tuple in Python. Using Tuple within a Tuple in PythonBelow are some of the ways by which we
4 min read
Python Program to Removes Every Element From A String List Except For a Specified letter
Given a List that contains only string elements, the following program shows methods of how every other alphabet can be removed from elements except for a specific one and then returns the output. Input : test_list = ["google", "is", "good", "goggled", "god"], K = 'g' Output : ['gg', '', 'g', 'ggg', 'g'] Explanation : All characters other than "g"
4 min read