Python - Product of elements using Index list
Last Updated :
28 Apr, 2025
Accessing an element from its index is easier task in python, just using the [] operator in a list does the trick. But in certain situations we are presented with tasks when we have more than once indices and we need to get all the elements corresponding to those indices and then perform the multiplication. Lets discuss certain ways to achieve this task.
Method #1 : Using List comprehension + loop
This task is easy to perform with a loop, and hence shorthand for it is the first method to start with this task. Iterating over the index list to get the corresponding elements from list into new list is brute method to perform this task. The task of product is performed using loop.
Python3
# Python3 code to demonstrate
# Product of Index values
# using list comprehension + loop
# Getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# Initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
# Printing original lists
print ("Original list : " + str(test_list))
print ("Original index list : " + str(index_list))
# Product of Index values
# using list comprehension + loop
res_list = prod([test_list[i] for i in index_list])
# Printing result
print ("Resultant list : " + str(res_list))
Output : Original list : [9, 4, 5, 8, 10, 14]
Original index list : [1, 3, 4]
Resultant list : 320
Time Complexity: O(n) where n is the length of the index_list.
Auxiliary Space: O(1) as only a few variables are used and no additional data structure is used.
Method #2 : Using map() + __getitem__ + loop
Yet another method to achieve this particular task is to map one list with other and get items of indexes and get corresponding matched elements from the search list. This is quite quick way to perform this task. The task of product is performed using loop.
Python3
# Python3 code to demonstrate
# Product of Index values
# using map() + __getitem__ + loop
# getting Product
def prod(val):
res = 1
for ele in val:
res *= ele
return res
# Initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
# Printing original lists
print("Original list : " + str(test_list))
print("Original index list : " + str(index_list))
# Product of Index values
# using map() + __getitem__ + loop to
res_list = prod(list(map(test_list.__getitem__, index_list)))
# Printing result
print("Resultant list : " + str(res_list))
Output : Original list : [9, 4, 5, 8, 10, 14]
Original index list : [1, 3, 4]
Resultant list : 320
Time Complexity: O(n), where n is the number of elements in the index_list.
Auxiliary Space: O(n), where n is the number of elements in the index_list.
Method #3 : Using reduce() of functools and operator
Python3
# Python3 code to demonstrate
# Product of Index values
# initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
# printing original lists
print ("Original list : " + str(test_list))
print ("Original index list : " + str(index_list))
x=[]
for i in index_list:
x.append(test_list[i])
from functools import reduce
import operator
res=reduce(operator.mul,x, 1)
# printing result
print ("Resultant list : " + str(res))
OutputOriginal list : [9, 4, 5, 8, 10, 14]
Original index list : [1, 3, 4]
Resultant list : 320
Time complexity: O(n), where n is the number of elements in the index list.
Auxiliary space: O(m), where m is the number of elements in the index list.
Method 5: Using numpy
Python3
#Importing NumPy
import numpy as np
#Initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
#Get product using NumPy
result = np.prod(np.array(test_list)[index_list])
#Printing result
print("Resultant list :", result)
Output:
Resultant list : 320
Time complexity: O(n)
Auxiliary Space: O(n)
Method #6: Using a for loop and the math library
Approach:
- Import the math library using import math.
- Initialize a variable named product to 1.
- Loop through each index in the index_list using a for loop.
- Access the corresponding element in test_list using the current index and multiply it with the product variable.
- After the loop, print the product variable to get the result.
Below is the implementation of the above approach:
Python3
import math
#Initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
#Calculating the product using a for loop and the math library
product = 1
for i in index_list:
product *= test_list[i]
#Printing result
print("Resultant list :", product)
OutputResultant list : 320
Time complexity: O(n), where n is the length of index_list.
Auxiliary space: O(1), as we only use a constant amount of extra memory to store the product variable.
Method #6: Using a lambda function and reduce()
Approach:
- Import the reduce() function from functools.
- Initialize the test_list and index_list as given in the problem statement.
- Define a lambda function that takes two arguments and returns their product.
- Use the reduce() function with the lambda function and a list comprehension to calculate the product of the elements of test_list at the indices given in index_list.
- Assign the product to a variable and print it.
Python3
from functools import reduce
# Initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
# Defining a lambda function for product
prod_lambda = lambda x, y: x * y
# Calculating the product using reduce() and a list comprehension
product = reduce(prod_lambda, [test_list[i] for i in index_list])
# Printing result
print("Resultant list :", product)
OutputResultant list : 320
Time complexity: O(n) where n is the length of the index_list.
Auxiliary space: O(m) where m is the length of the index_list, as we are storing a list of m elements extracted from the test_list.
Method #7: Using the itertools library
- Import necessary modules:
- reduce function from functools module to perform a specific operation (in this case, multiplication) on all elements of a list.
itemgetter function from operator module to extract elements from a list using indices.
combinations function from itertools module to generate all possible combinations of indices.
Initialize the test_list and index_list variables: - test_list is a list of integers.
index_list is a list of integers representing the indices of elements to be extracted from test_list.
Define a lambda function prod_lambda that takes a sublist and returns the product of all its elements using the reduce function. - Generate all possible combinations of indices using the combinations function and store the result in the index_combinations variable.
- Extract corresponding elements of test_list for each combination of indices using the itemgetter function and store the result in the sub_lists variable. For each combination, the itemgetter function is called with the indices as argument to extract the corresponding elements from test_list, and the resulting sublist is passed to prod_lambda to compute its product.
- Take the maximum of the resulting sublists using the max function and store the result in the product variable.
- Print the maximum product obtained from all the sublists using the print function.
Python3
from functools import reduce
from operator import itemgetter
from itertools import combinations
# Initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
# Define lambda function for product
def prod_lambda(sub_list): return reduce(lambda x, y: x * y, sub_list)
# Generate all possible combinations of indices
index_combinations = combinations(index_list, len(index_list))
# Extract corresponding elements of test_list for each combination of indices
sub_lists = [prod_lambda(itemgetter(*indices)(test_list))
for indices in index_combinations]
# Take the maximum of the resulting sublists
product = max(sub_lists)
# Printing result
print("Resultant list :", product)
OutputResultant list : 320
Time complexity: O(n^2), where n is the length of index_list.
Auxiliary space: O(1)
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
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