Given a matrix (or 2D list) of numbers, the task is to find the product of all its elements.
For example:
a = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
Product: 1622880
Let’s explore different methods to calculate the matrix product one by one.
Using numpy.prod()
numpy.prod() from numpy library, calculates the product of all elements in an array or flattened list, making it ideal for large datasets.
Python
import numpy as np
a = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
b = [ele for sub in a for ele in sub]
res = np.prod(b)
print(res)
Explanation:
- b = [ele for sub in a for ele in sub] flattens the 2D list into a one-dimensional list.
- np.prod(b) multiplies all elements and returns the total product.
Using math.prod()
The math.prod() function (available from Python 3.8+) provides a built-in way to multiply all elements in an iterable directly, making the code simpler and more efficient than using reduce.
Python
import math
a = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
b = [ele for sub in a for ele in sub]
res = math.prod(b)
print(res)
Explanation: math.prod() automatically multiplies all elements in b.
Using operator.mul with reduce()
Instead of using a lambda, you can use operator.mul for faster multiplication since it avoids lambda overhead.
Python
from functools import reduce
import operator
a = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
b = [ele for sub in a for ele in sub]
res = reduce(operator.mul, b, 1)
print(res)
Explanation: reduce(operator.mul, b, 1) multiplies all values in b starting from 1.
The reduce() function from the functools module applies a function cumulatively to the elements of an iterable, effectively reducing it to a single value. Here, it multiplies all flattened elements one by one.
Python
from functools import reduce
a = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
b = [ele for sub in a for ele in sub]
res = reduce(lambda x, y: x * y, b)
print(res)
Explanation: b = [ele for sub in a for ele in sub] flattens the matrix a into a one-dimensional list b. Then, reduce(lambda x, y: x * y, b) multiplies all elements of b cumulatively
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice