The Wayback Machine - https://web.archive.org/web/20241126013952/https://www.geeksforgeeks.org/python-adding-tuple-to-list-and-vice-versa/
Open In App

Python – Adding Tuple to List and vice – versa

Last Updated : 26 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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] 
This operator can be used to join a list with a tuple. Internally its working is similar to that of list.extend(), which can have any iterable as its argument, tuple in this case.

Python3
# Python3 code to demonstrate working of 
# Adding Tuple to List and vice - versa
# Using += operator (list + tuple)

# initializing list
test_list = [5, 6, 7]

# printing original list
print("The original list is : " + str(test_list))

# initializing tuple 
test_tup = (9, 10)

# Adding Tuple to List and vice - versa
# Using += operator (list + tuple)
test_list += test_tup

# printing result 
print("The container after addition : " + str(test_list)) 

Output
The original list is : [5, 6, 7]
The container after addition : [5, 6, 7, 9, 10]

Time complexity: O(1) – The += operator takes constant time to add a tuple to a list.
Auxiliary space: O(1) – No additional space is used, as the original list and tuple are modified in place.

Method #2 : Using tuple(), data type conversion [tuple + list] 
The following technique is used to add list to a tuple. The tuple has to converted to list and list has to be added, at last resultant is converted to tuple.

Python3
# Python3 code to demonstrate working of 
# Adding Tuple to List and vice - versa
# Using tuple(), data type conversion [tuple + list]

# initializing list
test_list = [5, 6, 7]

# printing original list
print("The original list is : " + str(test_list))

# initializing tuple 
test_tup = (9, 10)

# Adding Tuple to List and vice - versa
# Using tuple(), data type conversion [tuple + list]
res = tuple(list(test_tup) + test_list)

# printing result 
print("The container after addition : " + str(res)) 

Output
The original list is : [5, 6, 7]
The container after addition : (9, 10, 5, 6, 7)

Time complexity: O(1) – the code has a constant runtime that is not dependent on the size of the input.
Auxiliary space: O(n) – the space complexity of the code is dependent on the size of the input list.

Method #3: Using tuple(),list() and extend() methods

Python3
# Python3 code to demonstrate working of
# Adding Tuple to List and vice - versa

# initializing list and tuple
test_list = [5, 6, 7]
test_tup = (9,10)

# printing original list
print("The original list is : " + str(test_list))

# Adding Tuple to List 
test_list.extend(list(test_tup))
# printing result
print("The container after addition : " + str(test_list))

#*********************************************************

# initializing list and tuple
test_list = [1,2,3,4]
test_tup=(5,6)

# printing original tuple
print("The original tuple is : " + str(test_tup))

#Adding list to tuple
test_tup=list(test_tup)
test_tup.extend(test_list)
test_tup=tuple(test_tup)
# printing result
print("The container after addition : " + str(test_tup))

Output
The original list is : [5, 6, 7]
The container after addition : [5, 6, 7, 9, 10]
The original tuple is : (5, 6)
The container after addition : (5, 6, 1, 2, 3, 4)

Time complexity: O(n), where n is the size of the tuple being added.
Auxiliary space: O(n), where n is the size of the tuple being added.

METHOD 4:Using the insert() method: The given code defines a list my_list and a tuple my_tuple. It then inserts the tuple at index 3 of the list using the insert() method and prints the modified list.

  1. Define a list my_list with elements 5, 6, and 7.
  2. Define a tuple my_tuple with elements 9 and 10.
  3. Define a variable index and set it to 3.
  4. Call the insert() method on my_list and pass index and my_tuple as arguments.
  5. Print the modified list.
Python3
my_list = [5, 6, 7]
my_tuple = (9, 10)

index = 3
my_list.insert(index, my_tuple)

print("List after addition: ", my_list)

Output
List after addition:  [5, 6, 7, (9, 10)]

Time Complexity: O(n)

Space Complexity: O(1)

Method 5:Using zip and sum

The code defines a list original_list with elements [5, 6, 7] and a tuple tuple_to_add with elements (9, 10). It combines elements from both collections in two ways:

  • Adding Tuple to List: It pairs elements from original_list and tuple_to_add using zip, flattens the paired elements into a single sequence, and converts this sequence back into a list named list_with_tuple.
  • Adding List to Tuple: It pairs elements in a similar manner but converts the flattened sequence into a tuple named tuple_with_list.
  • Displaying Results: It prints original_list, list_with_tuple, and tuple_with_list to show the outcomes of these operations.
Python
original_list = [5, 6, 7]
tuple_to_add = (9, 10)

# Adding tuple to list
list_with_tuple = list(sum(zip(original_list, tuple_to_add), ()))

# Adding list to tuple
tuple_with_list = tuple(sum(zip(original_list, list(tuple_to_add)), ()))

# Displaying the results
print("The original list is:", original_list)
print("List with added tuple:", list_with_tuple)
print("Tuple with added list:", tuple_with_list)

Output
('The original list is:', [5, 6, 7])
('List with added tuple:', [5, 9, 6, 10])
('Tuple with added list:', (5, 9, 6, 10))

Time Complexity: O(n)

Space Complexity: O(n)



Previous Article
Next Article

Similar Reads

Python - Test String in Character List and vice-versa
Given a String, check if it's present in order in the character list and vice versa. Input : test_str = 'geeks', K = ['g', 'e', 'e', 'k', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] [ String in Character list ] Output : True Explanation : geeks is present in list , starting from 7th index till end. Input : test_str = 'geeksforgeeks', K = ['g', 'e', 'e'
3 min read
Python - Find the difference of the sum of list elements that are missing from Matrix and vice versa
Given a list and a Matrix, the task is to write a Python program that can find the difference of the sum of list elements that are missing from Matrix and vice versa. A simpler explanation says, find and sum all elements found in Matrix but not in list. Next, find and sum all elements found in list which are not in matrix. Perform difference betwee
7 min read
Convert files from jpg to png and vice versa using Python
Prerequisite: Pillow Library Sometime it is required to attach the Image where we required an image file with the specified extension. And we have the image with a different extension which needs to be converted with a specified extension like in this we will convert the image having an Extension of PNG to JPG and Vice-Versa. And Also we will be cr
3 min read
Python - Convert Image to String and vice-versa
To store or transfer an Image to some we need to convert it into a string such that the string should portray the image which we give as input. So In Python to do this Operation, it is a straight forward task not complicated because we have a lot of functions in Python available. Convert Image To StringHere First We Import "Base64" Method To Encode
2 min read
Python program to convert meters in yards and vice versa
Given the distance in either meter or yard, the task here is to generate a Python program that converts distance given in meters to yards and vice versa. Examples: Input: Length in Meter: 245 Length in Yard : 100 Output: 245 Meter in Yard = 267.9344 100 Yards in Meter = 91.4403 Input: Length in Meter: 5 Length in Yard : 20 Output: 5 Meter in Yard =
2 min read
Convert files from jpg to gif and vice versa using Python
Sometimes it is required to attach the Image where we required image file with the specified extension. And we have the image with the different extension which needs to be converted with a specified extension like in this we will convert the image having Extension of .jpg to .gif and Vice-Versa And Also we will be creating the GUI interface to the
3 min read
Convert the .PNG to .GIF and it's vice-versa in Python
Prerequisites: PILTkinter Python supports subsystems for converting one file format to another. This article discusses this topic and depicts how a png file can be converted to its gif equivalent and vice versa. For conversion of one file format to the other PIL is employed. The given example uses a GUI interface to the code, so we will require Tki
2 min read
Convert the .GIF to .BMP and it's vice-versa in Python
Sometimes it is required to attach the Image where we required an image file with the specified extension. And we have the image with the different extension which needs to be converted with a specified extension like in this we will convert the image having Extension of .bmp to .gif and Vice-Versa. In this article, we are going to convert .GIF to
3 min read
How to Move a Torch Tensor from CPU to GPU and Vice Versa in Python?
In this article, we will see how to move a tensor from CPU to GPU and from GPU to CPU in Python. Why do we need to move the tensor? This is done for the following reasons: When Training big neural networks, we need to use our GPU for faster training. So PyTorch expects the data to be transferred from CPU to GPU. Initially, all data are in the CPU.
2 min read
Binary to decimal and vice-versa in python
Write Python code for converting a decimal number to it's binary equivalent and vice-versa. Example: From decimal to binary Input : 8 Output : 1 0 0 0 From binary to decimal Input : 100 Output : 4 Decimal to binary Keep calling conversion function with n/2 till n > 1, later perform n % 1 to get MSB of converted binary number. Example :- 7 1). 7/
4 min read
Convert string to DateTime and vice-versa in Python
A common necessity in many programming applications is dealing with dates and times. Python has strong tools and packages that simplify handling date and time conversions. This article will examine how to effectively manipulate and format date and time values in Python by converting Strings to Datetime objects and back. We will cover the article in
6 min read
Convert IP address to integer and vice versa
We will use the ipaddress module for this purpose. ipaddress is a module that helps in the creation, manipulation and operation on IPv4 and IPv6 addresses and networks. The motivation of converting IP Addresses to integers and vice versa is that other modules that use IP addresses (such as socket) usually won’t accept objects from ipaddress module
2 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 - 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 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 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 program to convert tuple into list by adding the given string after every element
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
5 min read
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 | 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 - 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
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 - 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
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 | 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 | Pair and combine nested list to tuple list
Sometimes we need to convert between the data types, primarily due to the reason of feeding them to some function or output. This article solves a very particular problem of pairing like indices in list of lists and then construction of list of tuples of those pairs. Let's discuss how to achieve the solution of this problem. Method #1 : Using zip()
10 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 | 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
three90RightbarBannerImg