Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Product of Squares in List
Next article icon

Python - Product of elements using Index list

Last Updated : 25 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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)) 

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(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:

  1. Import the math library using import math.
  2. Initialize a variable named product to 1.
  3. 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.
  4. 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) 

Output
Resultant 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:

  1. Import the reduce() function from functools.
  2. Initialize the test_list and index_list as given in the problem statement.
  3. Define a lambda function that takes two arguments and returns their product.
  4. 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.
  5. 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) 

Output
Resultant 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

  1. Import necessary modules:
  2. 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:
  3. 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.
  4. Generate all possible combinations of indices using the combinations function and store the result in the index_combinations variable.
  5. 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.
  6. Take the maximum of the resulting sublists using the max function and store the result in the product variable.
  7. 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) 

Output
Resultant list : 320

Time complexity: O(n^2), where n is the length of index_list.
Auxiliary space: O(1)


Next Article
Python | Product of Squares in List
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Index match element Product
    Sometimes, while working with Python list we can have a problem in which we have to compare two lists for index similarity and hence can have a task of multiplication equal index pairs. Let’s discuss certain way in which this task can be performed. Method #1 : Using loop + zip() This task can be per
    2 min read
  • Python - Maximum product using K elements
    Sometimes, while working with Python lists, we can have a problem in which we need to maximize certain numbers. There can be many conditions of maximizing. Example of that is maximizing product by using K elements. Lets discuss certain ways in which this can be performed. Method #1 : Using max() + s
    4 min read
  • Python | Product of Squares in List
    Python being the language of magicians can be used to perform many tedious and repetitive tasks in an easy and concise manner and have the knowledge to utilize this tool to the fullest is always useful. One such small application can be finding product of squares of list in just one line. Let’s disc
    5 min read
  • Python | Column Product in List of lists
    Sometimes, we are encountered with such problem in which we need to find the product of each column in a matrix i.e product of each index in list of lists. This kind of problem is quite common and useful in competitive programming. Let’s discuss certain ways in which this problem can be solved. Meth
    6 min read
  • Python - Product of i^k in List
    Python being the language of magicians can be used to perform many tedious and repetitive tasks in a easy and concise manner and having the knowledge to utilize this tool to the fullest is always useful. One such small application can be finding product of i^k of list in just one line. Let’s discuss
    5 min read
  • Python | Cartesian product of string elements
    Sometimes, while working with Python strings, we can have problem when we have data in a string that is a comma or any delim separated. We might want to perform a cartesian product with other similar strings to get all possible pairs of data. Let us discuss certain ways in which this task can be per
    5 min read
  • Python - Row Summation of Like Index Product
    Given a Matrix and elements list, For every row, extract the summation of product of elements with argument list. Input : test_list = [[4, 5], [1, 5], [8, 2]], mul_list = [5, 2, 3] Output : [30, 15, 44] Explanation : For 1st row, (4*5) + (5*2) = 30, as value of 1st element of result list. This way e
    4 min read
  • Python - Index Ranks of Elements
    Given a list of elements, our task is to get the index ranks of each element. [Tex]Index Rank of Number = (Sum of occurrence indices of number) / number[/Tex] Input : test_list = [3, 4, 6, 5, 3, 4, 9, 1, 2, 1, 8, 3, 2, 3, 9] Output : [(1, 16.0), (2, 10.0), (3, 9.333333333333334), (4, 1.5), (5, 0.6),
    3 min read
  • Python - Cubes Product in list
    Python being the language of magicians can be used to perform many tedious and repetitive tasks in a easy and concise manner and having the knowledge to utilize this tool to the fullest is always useful. One such small application can be finding product of cubes of list in just one line. Let’s discu
    5 min read
  • Python - Suffix Product in list
    We are given a list of numbers, and our task is to compute the suffix product for each position in the list. The suffix product at any index is the product of all elements to the right, including the element at that index. For example, given a = [2, 3, 4, 5], the suffix products would be [120, 60, 2
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences