Python | Column Product in List of lists
Last Updated :
16 May, 2023
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.
Method #1: Using loop + list comprehension + zip()
The combination of above methods are required to solve this particular problem. The explicit product function is used to get the required product value and zip function provides the combination of like indices and then list is created using list comprehension.
Python3
# Python3 code to demonstrate
# Column Product in List of lists
# using loop + list comprehension + zip()
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initializing list
test_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
# printing original list
print("The original list : " + str(test_list))
# using loop + list comprehension + zip()
# Column Product in List of lists
res = [prod(idx) for idx in zip(*test_list)]
# print result
print("The Product of each index list is : " + str(res))
Output : The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Product of each index list is : [27, 63, 60]
Time complexity: O(n^2)
Auxiliary space: O(n)
Method #2: Using map() + loop + zip()
This works in almost similar way as the above method, but the difference is just that we use map function to build the product list rather than using list comprehension.
Python3
# Python3 code to demonstrate
# Column Product in List of lists
# using map() + loop + zip()
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initializing list
test_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
# printing original list
print("The original list : " + str(test_list))
# using map() + loop + zip()
# Column Product in List of lists
res = list(map(prod, zip(*test_list)))
# print result
print("The Product of each index list is : " + str(res))
Output : The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Product of each index list is : [27, 63, 60]
Time complexity: O(n^2), where n is the length of the inner lists.
Auxiliary space: O(n), where n is the length of the longest inner list.
Method #3 : Using functors.reduce() and operator.mul
Python3
# Python3 code to demonstrate
# Column Product in List of lists
# initializing list
test_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
# printing original list
print("The original list : " + str(test_list))
# Column Product in List of lists
res=[]
for i in range(0,len(test_list)):
a=[]
for j in range(0,len(test_list[i])):
x=test_list[j][i]
a.append(x)
from functools import reduce
import operator
b=reduce(operator.mul, a, 1)
res.append(b)
# print result
print("The Product of each index list is : " + str(res))
OutputThe original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Product of each index list is : [27, 63, 60]
Time complexity: O(n^2), where n is the length of the input list
Auxiliary space: O(n), where n is the length of the input list.
Method #4: Using numpy.prod()
Note: Install numpy module using command "pip install numpy"
This method is recommended if the product of large array needs to be calculated. Here, numpy.prod() is used to get the product of each index.
Python3
# Python3 code to demonstrate
# Column Product in List of lists
# using numpy.prod()
# importing numpy
import numpy as np
# initializing list
test_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
# printing original list
print("The original list : " + str(test_list))
# using numpy.prod()
# Column Product in List of lists
res = [np.prod(idx) for idx in zip(*test_list)]
# print result
print("The Product of each index list is : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
Output
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Product of each index list is : [27, 63, 60]
Time Complexity: O(M*N)
Auxiliary Space: O(M*N)
Method #5: Using for loops
Python3
# Python3 code to demonstrate
# Column Product in List of lists
# initializing list
test_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
# printing original list
print("The original list : " + str(test_list))
# Column Product in List of lists
res=[]
for i in range(0,len(test_list)):
p=1
for j in range(0,len(test_list[i])):
p*=test_list[j][i]
res.append(p)
# print result
print("The Product of each index list is : " + str(res))
OutputThe original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Product of each index list is : [27, 63, 60]
Time complexity: O(n^2)
Auxiliary space: O(n)
Method #6: Using the pandas library:
- Import the pandas library using the import pandas as pd statement.
- Define the input list of lists as list_of_lists = [[3, 7, 6], [1, 3, 5], [9, 3, 2]].
- Convert the list of lists to a pandas DataFrame using the pd.DataFrame() function and store it in the variable df.
- Compute the column products using the prod() method of the DataFrame df, which calculates the product of each column along the 0 axis (i.e., the columns), and store it in the variable column_products.
- Convert the resulting pandas Series to a regular Python list using the tolist() method and store it back in column_products.
- Print the column products using the print() statement, along with an appropriate message.
Python3
import pandas as pd
# Given input
list_of_lists = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
# Converting the list of lists to a DataFrame
df = pd.DataFrame(list_of_lists)
# Computing the column products using pandas
column_products = df.prod(axis=0).tolist()
# Printing the column products
print("The product of each column is:", column_products)
Output:
The product of each column is: [27, 63, 60]
Time complexity: O(NM), where N is the number of rows and M is the number of columns in the input list of lists.
Auxiliary space: O(NM), as the input list of lists is first converted to a pandas
Similar Reads
Python | Product of kth column in List of Lists
Sometimes, while working with Python Matrix, we may have a problem in which we require to find the product of a particular column. This can have a possible application in day-day programming and competitive programming. Letâs discuss certain ways in which this task can be performed. Method #1 : Usin
4 min read
Python - Kth Column Product in Tuple List
Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the product of itâs Kth index. This problem has application in web development domain while working with data informations. Letâs discuss certain ways in which this task can be performed. M
7 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 - 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
Flatten a List of Lists in Python
Flattening a list of lists means turning a nested list structure into a single flat list. This can be useful when we need to process or analyze the data in a simpler format. In this article, we will explore various approaches to Flatten a list of Lists in Python.Using itertools.chain itertools modul
3 min read
Python - Product of elements using Index list
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 multipl
7 min read
Python - Product of consecutive pairs in list
Sometimes, while working with Python list, one can have a problem in which one needs to find perform the product of list in pair form. This is useful as a subproblem solution of bigger problem in web development and day-day programming. Letâs discuss certain ways in which this problem can be solved.
7 min read
Python | Nth column Matrix Product
Sometimes, while working with Python Matrix, we may have a problem in which we require to find the product of a particular column. This can have a possible application in day-day programming and competitive programming. Letâs discuss certain ways in which this task can be performed. Method #1: Using
7 min read
Python | Product of Prefix in list
Nowadays, especially in competitive programming, the utility of computing prefix product is quite popular and features in many problems. Hence, having a one-liner solution to it would possess a great help. Letâs discuss certain ways in which this problem can be solved. Method 1: Using list comprehen
4 min read
Python - Cumulative product of dictionary value lists
Sometimes, while working with Python dictionaries, we can have itâs values as lists. In this can we can have a problem that we just require the product of elements in those list as a whole. This can be a problem in Data Science in which we need to get total records in observations. Letâs discuss cer
4 min read