Python - Add list elements to tuples list
Last Updated :
08 May, 2023
Sometimes, while working with Python tuples, we can have a problem in which we need to add all the elements of a particular list to all tuples of a list. This kind of problem can come in domains such as web development and day-day programming. Let's discuss certain ways in which this task can be done.
Input : test_list = [(5, 6), (2, 4), (5, 7), (2, 5)], sub_list = [5, 4]
Output : [(5, 6, 5, 4), (2, 4, 5, 4), (5, 7, 5, 4), (2, 5, 5, 4)]
Input : test_list = [(5, 6), (2, 4), (5, 7), (2, 5)], sub_list = [5]
Output : [(5, 6, 5), (2, 4, 5), (5, 7, 5), (2, 5, 5)]
Method #1 : Using list comprehension + "+" operator
The combination of above functionalities can be used to solve this problem. In this, we perform task of adding tuple to list using "+" operator and iteration over all tuples is done using list comprehension.
Python3
# Python3 code to demonstrate working of
# Add list elements to tuples list
# Using list comprehension + "+" operator
# initializing list
test_list = [(5, 6), (2, 4), (5, 7), (2, 5)]
# printing original list
print("The original list is : " + str(test_list))
# initializing list
sub_list = [7, 2, 4, 6]
# Add list elements to tuples list
# Using list comprehension + "+" operator
res = [sub + tuple(sub_list) for sub in test_list]
# printing result
print("The modified list : " + str(res))
Output : The original list is : [(5, 6), (2, 4), (5, 7), (2, 5)]
The modified list : [(5, 6, 7, 2, 4, 6), (2, 4, 7, 2, 4, 6), (5, 7, 7, 2, 4, 6), (2, 5, 7, 2, 4, 6)]
Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(n), as it creates a new list res of the same length as the input list test_list. Additionally, it also creates a new list sub_list of length m (the length of the input list sub_list), but this is not dependent on the size of the input and is therefore considered constant space.
Method #2 : Using list comprehension + "*" operator
The combination of above functions can be used to solve this problem. In this, we perform the task of adding list to a tuple using pack-unpack operator "*". This is more efficient method than above method.
Python3
# Python3 code to demonstrate working of
# Add list elements to tuples list
# Using list comprehension + "*" operator
# initializing list
test_list = [(5, 6), (2, 4), (5, 7), (2, 5)]
# printing original list
print("The original list is : " + str(test_list))
# initializing list
sub_list = [7, 2, 4, 6]
# Add list elements to tuples list
# Using list comprehension + "*" operator
res = [(*sub, *sub_list) for sub in test_list]
# printing result
print("The modified list : " + str(res))
Output : The original list is : [(5, 6), (2, 4), (5, 7), (2, 5)]
The modified list : [(5, 6, 7, 2, 4, 6), (2, 4, 7, 2, 4, 6), (5, 7, 7, 2, 4, 6), (2, 5, 7, 2, 4, 6)]
Time complexity: O(n), where n is the length of the input list 'test_list'.
Auxiliary space: O(n), where n is the length of the input list 'test_list'.
Method 3 : using a nested for loop.
- Initialize a list of tuples named test_list with elements (5, 6), (2, 4), (5, 7), (2, 5).
- Initialize a list named sub_list with elements 7, 2, 4, 6.
- Initialize an empty list named res.
- Start a for loop that iterates over each tuple in test_list.
- For each tuple in test_list, create a new empty tuple named new_tup.
- Start a nested for loop that iterates over each element in the current tuple.
- For each element in the current tuple, append it to new_tup.
- Start another nested for loop that iterates over each element in sub_list.
- For each element in sub_list, append it to new_tup.
- After all elements have been appended to new_tup, append the tuple to res.
- After all tuples in test_list have been processed, print the modified list by converting res to a string and concatenating it to a string "The modified list : ".
- End the program.
Python3
test_list = [(5, 6), (2, 4), (5, 7), (2, 5)]
sub_list = [7, 2, 4, 6]
res = []
# Loop through each tuple in the test_list
for tup in test_list:
new_tup = ()
# Loop through each element in the tuple and add it to the new tuple
for ele in tup:
new_tup += (ele,)
# Add the sub_list to the new tuple
for ele in sub_list:
new_tup += (ele,)
# Append the new tuple to the result list
res.append(new_tup)
# Print the result
print("The modified list : " + str(res))
OutputThe modified list : [(5, 6, 7, 2, 4, 6), (2, 4, 7, 2, 4, 6), (5, 7, 7, 2, 4, 6), (2, 5, 7, 2, 4, 6)]
The time complexity of this approach is O(n^2), where n is the length of the test_list.
The auxiliary space complexity is O(n), as we need to store the modified tuples in a new list.
METHOD 4: Using map(), lambda function, and tuple concatenation
APPROACH:
This program takes a list of tuples as input and adds a new set of elements to each tuple. Then it returns the modified list of tuples as output.
ALGORITHM:
1. Define the original list of tuples.
2. Define the modified list as an empty list.
3. Iterate through each tuple in the original list.
4. Convert each tuple to a list.
5. Append the new set of elements to the list.
6. Convert the modified list back to a tuple.
7. Append the modified tuple to the modified list.
8. Return the modified list.
Python3
original_list = [(5, 6), (2, 4), (5, 7), (2, 5)]
modified_list = list(map(lambda x: tuple(list(x) + [7, 2, 4, 6]), original_list))
print("The modified list:", modified_list)
OutputThe modified list: [(5, 6, 7, 2, 4, 6), (2, 4, 7, 2, 4, 6), (5, 7, 7, 2, 4, 6), (2, 5, 7, 2, 4, 6)]
Time complexity: O(n), where n is the length of the original list.
Space complexity: O(n), where n is the length of the original list.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read