Python - Product of Selective Tuple Keys
Last Updated :
03 May, 2023
Sometimes, while using a list of tuples, we come across a problem in which we have a certain list of keys and we just need the product of values of those keys from the list of tuples. This has a utility in rating or product of specific entities. Let’s discuss certain ways in which this can be done.
Method #1: Using dict() + loop + get() + list comprehension
We can perform this particular task by first, converting the list into the dictionary and then employing list comprehension to get the value of specific keys using the get function. The product of values is performed using a loop.
Python3
# Python3 code to demonstrate
# Product of Selective Tuple Keys
# using dict() + get() + list comprehension + loop
# getting Product
def prod(val):
res = 1
for ele in val:
res *= ele
return res
# Initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# Initializing selection list
select_list = ['Nikhil', 'Akshat']
# Printing original list
print("The original list is: "+ str(test_list))
# Printing selection list
print("The selection list is : " + str(select_list))
# Product of Selective Tuple Keys
# using dict() + get() + list comprehension + loop
temp = dict(test_list)
res = prod([temp.get(i, 0) for i in select_list])
# Printing the result
print("The selective values product of keys : " + str(res))
OutputThe original list is: [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values product of keys : 3
Time complexity: O(n)
Auxiliary space: O(n)
Method #2: Using next() + loop + list comprehension
This particular problem can be solved using the next function which performs the iteration using the iterators and hence more efficient way to achieve a possible solution. The product of values is performed using loop.
Python3
# Python3 code to demonstrate
# Product of Selective Tuple Keys
# using next() + list comprehension + loop
# Function to get the product
def prod(val):
res = 1
for ele in val:
res *= ele
return res
# Initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# Initializing selection list
select_list = ['Nikhil', 'Akshat']
# Printing original list
print("The original list is : " + str(test_list))
# Printing selection list
print("The selection list is : " + str(select_list))
# Product of Selective Tuple Keys
# using next() + list comprehension + loop
res = prod([next((sub[1] for sub in test_list if sub[0] == i), 0)
for i in select_list])
# Printing the result
print("The selective values product of keys : " + str(res))
OutputThe original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values product of keys : 3
Time Complexity: O(N * M), where n is the length of the test_list and m is the length of the select_list.
Auxiliary Space: O(M), where m is the length of the select_list.
Method #3: Using for loop and in operator
Python3
# Python3 code to demonstrate
# Product of Selective Tuple Keys
# Initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# Initializing selection list
select_list = ['Nikhil', 'Akshat']
# Printing original list
print("The original list is : " + str(test_list))
# Printing selection list
print("The selection list is : " + str(select_list))
# Product of Selective Tuple Keys
res = 1
for i in test_list:
if i[0] in select_list:
res *= i[1]
# Printing result
print("The selective values product of keys : " + str(res))
OutputThe original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values product of keys : 3
Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
Method #4 : Using map() and lambda() functions
Python3
def prod(val):
# Initialize a variable to store the product of values
res = 1
# Loop through each value in the input list
for ele in val:
# Multiply the current product by the current value
res *= ele
# Return the final product
return res
# Initialize a list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# Initialize a list of selected keys
select_list = ['Nikhil', 'Akshat']
# Create a dictionary from the list of tuples
temp = dict(test_list)
# Calculate the product of values of selected keys
# using a map and lambda function
# Printing original list
print("The original list is : " + str(test_list))
# Printing selection list
print("The selection list is : " + str(select_list))
result = prod(map(lambda x: temp.get(x, 0), select_list))
# Print the result
print("The selective values product of keys : " + str(result))
#This code is contributed by Jyothi pinjala
OutputThe original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values product of keys : 3
Time complexity: O(n)
Auxiliary Space: O(n)
Method #5: Using functools.reduce()+operator.mul+for loop
Python3
# Python3 code to demonstrate
# Product of Selective Tuple Keys
# initializing list of tuples
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
# initializing selection list
select_list = ['Nikhil', 'Akshat']
# printing original list
print("The original list is : " + str(test_list))
# printing selection list
print("The selection list is : " + str(select_list))
# Product of Selective Tuple Keys
res = []
for i in test_list:
if i[0] in select_list:
res.append(i[1])
from functools import reduce
import operator
res1=reduce(operator.mul,res,1)
# printing result
print("The selective values product of keys : " + str(res1))
OutputThe original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values product of keys : 3
Time complexity: O(n)
Auxiliary Space: O(n)
Method #6:Using Recursion
This code defines a function selective_product(tuples, selection) that takes a list of tuples and a list of strings selection as input and returns the product of values in the tuples that have keys that appear in the selection list. The function recursively traverses the input list of tuples, checks if the key of the current tuple is in the selection list, and if so, multiplies its value with the product of the remaining tuples. If the key is not in the selection list, the function recurses on the remaining tuples.
The code then defines an example input list of tuples test_list and a selection list select_list, calls the selective_product function on them, and prints the resulting product.
Python3
def selective_product(tuples, selection):
if len(tuples) == 0:
return 1
elif tuples[0][0] in selection:
return tuples[0][1] * selective_product(tuples[1:], selection)
else:
return selective_product(tuples[1:], selection)
# Example usage
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
select_list = ['Nikhil', 'Akshat']
# printing original list
print("The original list is : " + str(test_list))
# printing selection list
print("The selection list is : " + str(select_list))
res = selective_product(test_list, select_list)
print("The selective values product of keys : " + str(res))
#This code is contributed Vinay pinjala.
OutputThe original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values product of keys : 3
Time complexity: O(n)
Auxiliary Space: O(n)
Time complexity:
The function recurses over the input list of tuples. In the worst case, it needs to check each tuple once, so the worst-case time complexity is O(n), where n is the length of the input list.
Multiplying the values of selected tuples takes constant time, and the in operator used to check if the key is in the selection list also takes constant time.
Therefore, the overall time complexity of this function is O(n), where n is the length of the input list.
Auxiliary Space:
The function uses recursion to traverse the input list of tuples. In the worst case, the recursion depth is equal to the length of the input list, so the worst-case space complexity is O(n), where n is the length of the input list.
The function uses a constant amount of additional space for storing the selection list and temporary variables.
Therefore, the overall space complexity is O(n)
Method #5: Using list comprehension with conditional and reduce()
This method uses list comprehension to filter out the tuples whose first element is not in the select_list. Then it uses reduce() with the operator.mul function to multiply all the second elements of the filtered tuples.
Python3
from functools import reduce
import operator
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
select_list = ['Nikhil', 'Akshat']
res = [tup[1] for tup in test_list if tup[0] in select_list]
res1 = reduce(operator.mul, res, 1)
print("The selective values product of keys : " + str(res1))
OutputThe selective values product of keys : 3
The time complexity of this code is O(n), where n is the length of the test_list.
The auxiliary space complexity is O(k), where k is the length of the filtered list obtained from the list comprehension.
Method 8 : Using filter() and reduce()
Use the filter() function to create a new list of tuples where the key of each tuple is in the selection list.
Use the reduce() function from the functools module to multiply the values of the tuples in the new list.
Return the result.
Python3
import functools
def selective_product(tuples, selection):
selected_tuples = filter(lambda x: x[0] in selection, tuples)
selected_values = [t[1] for t in selected_tuples]
result = functools.reduce(lambda x, y: x * y, selected_values, 1)
return result
# Example usage
test_list = [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
select_list = ['Nikhil', 'Akshat']
# printing original list
print("The original list is : " + str(test_list))
# printing selection list
print("The selection list is : " + str(select_list))
res = selective_product(test_list, select_list)
print("The selective values product of keys : " + str(res))
# Output: The selective values product of keys : 3
OutputThe original list is : [('Nikhil', 1), ('Akash', 2), ('Akshat', 3), ('Manjeet', 4)]
The selection list is : ['Nikhil', 'Akshat']
The selective values product of keys : 3
Time complexity: O(n), where n is the length of the tuples list.
Auxiliary space: O(k), where k is the number of tuples whose keys are in the selection list.
Similar Reads
Python Tutorial - Learn Python Programming Language 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. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
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
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 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
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 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