Python | Nth column Matrix Product
Last Updated :
09 Apr, 2023
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 loop + zip()
This task can be solved using a combination of the above functions. In this, we pass in the zip() the list, to access all columns and loop to get the product of columns.
Step-by-step approach:
- Define a function prod(val) which takes a list val as input and returns the product of all the elements of the list.
- Define a 2D list test_list containing some values.
- Print the original list.
- Initialize a variable N with the value 2.
- Use a list comprehension to calculate the product of each column of the 2D list. To achieve this, we use the zip() function to group the elements of each column together, and then pass each group of elements to the prod() function to calculate their product. This is done using a loop that iterates over the zip(*test_list) which returns the transpose of the matrix.
- The result is a list containing the product of each column. The Nth element of this list is the product of the Nth column of the matrix.
- Print the product of the Nth column of the matrix.
Python3
# Python3 code to demonstrate working of
# Nth column Matrix Product
# using loop + zip()
def prod(val):
res = 1
for ele in val:
res *= ele
return res
# initialize list
test_list = [[5, 6, 7],
[9, 10, 2],
[10, 3, 4]]
# printing original list
print("The original list is : " + str(test_list))
# initialize N
N = 2
# Nth column Matrix Product
# using loop + zip()
res = [prod(idx) for idx in zip(*test_list)][N]
# printing result
print("Product of Nth column is : " + str(res))
OutputThe original list is : [[5, 6, 7], [9, 10, 2], [10, 3, 4]]
Product of Nth column is : 56
Time Complexity: O(N)
Auxiliary Space: O(1)
Method #2: Using loop
This is a brute-force way to solve this problem. In this, we iterate through the matrix and take the product of the column by testing the column number.
step-by-step approach
- Initialize a nested list test_list with integer elements.
- Print the original list test_list.
- Initialize a variable N to specify the column index for which to calculate the product.
- Initialize a variable res to 1, to hold the product of the Nth column elements.
- Iterate over each sub-list in test_list using a for loop.
- For each sub-list, iterate over each element using a for loop.
- Check if the current element index is equal to N.
- If the index is equal to N, multiply the current element value with the value of res.
- Print the final product value of the Nth column.
Python3
# Python3 code to demonstrate working of
# Nth column Matrix Product
# Using loop
# initialize list
test_list = [[5, 6, 7],
[9, 10, 2],
[10, 3, 4]]
# printing original list
print("The original list is : " + str(test_list))
# initialize N
N = 2
# Nth column Matrix Product
# Using loop
res = 1
for sub in test_list:
for idx in range(0, len(sub)):
if idx == N:
res = res * sub[idx]
# printing result
print("Product of Nth column is : " + str(res))
OutputThe original list is : [[5, 6, 7], [9, 10, 2], [10, 3, 4]]
Product of Nth column is : 56
Time Complexity: O(N2)
Auxiliary Space: O(1)
Method #3: Using Indexing and Single loop
Python3
# Python3 code to demonstrate working of
# Nth column Matrix Product
# Using loop
# initialize list
test_list = [[5, 6, 7],
[9, 10, 2],
[10, 3, 4]]
# printing original list
print("The original list is : " + str(test_list))
# initialize N
N = 2
# Nth column Matrix Product
# Using loop
res = 1
for i in test_list:
res = res * i[N]
# printing result
print("Product of Nth column is :" + str(res))
OutputThe original list is : [[5, 6, 7], [9, 10, 2], [10, 3, 4]]
Product of Nth column is :56
Time Complexity: O(N)
Auxiliary Space: O(1)
Method #4: Using reduce()
Python3
# Python3 code to demonstrate working of
# Nth column Matrix Product
# using reduce()
# import functools for reduce()
import functools
# initialize list
test_list = [[5, 6, 7],
[9, 10, 2],
[10, 3, 4]]
# printing original list
print("The original list is : " + str(test_list))
# initialize N
N = 2
# Nth column Matrix Product
# using reduce()
res = functools.reduce(lambda a, b: a * b[N], test_list, 1)
# printing result
print("Product of Nth column is : " + str(res))
# This code is contributed by Edula Vinay Kumar Reddy
Output:
The original list is : [[5, 6, 7], [9, 10, 2], [10, 3, 4]]
Product of Nth column is : 56
Time Complexity: O(N)
Auxiliary Space: O(1)
Method #5: Using NumPy
Use numpy.prod() function to find the product of all elements in a given axis.
Approach:
- Import NumPy library.
- Convert the list into a NumPy array.
- Extract the Nth column using array slicing.
- Find the product of elements in the Nth column using numpy.prod() function.
- Print the result.
Python3
import numpy as np
# initialize list
test_list = [[5, 6, 7],
[9, 10, 2],
[10, 3, 4]]
# printing original list
print("The original list is : " + str(test_list))
# initialize N
N = 2
# Nth column Matrix Product using NumPy
arr = np.array(test_list)
res = np.prod(arr[:, N])
# printing result
print("Product of Nth column is :" + str(res))
Output:
The original list is : [[5, 6, 7], [9, 10, 2], [10, 3, 4]]
Product of Nth column is :56
Time complexity: O(N), where N is the number of elements in the Nth column.
Auxiliary space: O(N), as we are creating a NumPy array to store the input list.
Method 6: Using itertools.islice() and map()
Step-by-step approach:
- Import the itertools library.
- Define the input matrix as a list of lists.
- Use itertools.islice() to extract the Nth column of the matrix as an iterator.
- Use map() and the prod() function (defined in Method #1) to calculate the product of the Nth column.
- Convert the result to a list and extract the first (and only) element.
- Print the result.
Python3
# Python3 code to demonstrate working of
# Nth column Matrix Product
# using itertools.islice() and map()
import itertools
def prod(val):
res = 1
for ele in val:
res *= ele
return res
# initialize list
test_list = [[5, 6, 7],
[9, 10, 2],
[10, 3, 4]]
# printing original list
print("The original list is : " + str(test_list))
# initialize N
N = 2
# Nth column Matrix Product
# using itertools.islice() and map()
res = list(map(prod, itertools.islice(
((row[N],) for row in test_list), len(test_list))))
# extract the first (and only) element of the result
res = res[0]
# printing result
print("Product of Nth column is : " + str(res))
OutputThe original list is : [[5, 6, 7], [9, 10, 2], [10, 3, 4]]
Product of Nth column is : 7
Time complexity: O(n), where n is the number of elements in the Nth column.
Auxiliary space: O(1), as only one variable (res) is used to store the result.
Similar Reads
Python | Matrix Tuple pair Column product
Sometimes, we encounter a problem where we deal with a complex type of matrix column product in which we are given a tuple and we need to perform the product of its like elements. This has a good application in Machine Learning domain. Letâs discuss certain ways in which this can be done. Method #1
4 min read
Matrix Product - Python
The task of calculating the matrix product in Python involves finding the product of all elements within a matrix or 2D list . This operation requires iterating through each element in the matrix and multiplying them together to obtain a single cumulative product. For example, given a matrix a = [[1
3 min read
Python | Uneven Sized Matrix Column product
The usual list of list, unlike conventional C type Matrix, can allow the nested list of lists with variable lengths, and when we require the product of its columns, the uneven length of rows may lead to some elements in that elements to be absent and if not handled correctly, may throw exception. Le
7 min read
Python | Search in Nth Column of Matrix
Sometimes, while working with Python Matrix, we can have a problem in which we need to check if an element is present or not. This problem is simpler, but a variation to it can be to perform a check in a particular column of Matrix. Let's discuss a shorthand by which this task can be performed. Met
10 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 | Nested List Intersection Matrix Product
The problem of finding the common elements in list of 2 lists is quite a common problem and can be dealt with ease and also has been discussed before many times. But sometimes, we require to find the elements that are in common from N lists and return their product. Letâs discuss certain ways in whi
3 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 | Get Kth Column of Matrix
Sometimes, while working with Python Matrix, one can have a problem in which one needs to find the Kth column of Matrix. This is a very popular problem in Machine Learning Domain and having solution to this is useful. Let's discuss certain ways in which this problem can be solved. Method #1 : Using
6 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 - Matrix creation of n*n
Matrices are fundamental structures in programming and are widely used in various domains including mathematics, machine learning, image processing, and simulations. Creating an nÃn matrix efficiently is an important step for these applications. This article will explore multiple ways to create such
3 min read