Python – Product of kth column in list of lists


The list can have any number of sublists within the square brackets and be separated by a comma. The elements that are once defined inside the list data structure that is within the square brackets cannot be changed. So, inside the list, we can store multiple values together and thus reducing the complex operations. The list can hold elements and another list called the sublists.

In this article, the process involved in multiplying the column element and to understand in a better way let’s take one example. The list consists of three sublist and contains three elements each. The programmer decides to produce all the elements in the index value of 2 which is the last element of each list.

List = [[1, 2, 3],
	[4, 5, 6],
	[7, 8, 9]]

To multiply the second index element that is 3*6*9 = 162 is the product returned. In the same way, the Python programs do the functionalities using different approaches and thus increasing the efficiency and reducing the time.

Approach

  • Approach 1 βˆ’ Using the for loop

  • Approach 2 βˆ’ Using the reduce method

Approach 1: Python Program to product the kth column in lists of lists using the for loop

The for loop will iterate through the given list of elements and find the product for the specified index value of the lists of lists.

Algorithm

  • Step 1 βˆ’ The function is defined with two arguments

  • Step 2 βˆ’ Using the isinstance(), we can check whether the given input is present in the list or not

  • Step 3 βˆ’ In the below code, it is mentioned as 2, so the result is printed and the other hand when the value more than 2 is mentioned it executes the return statement.

  • Step 4 βˆ’ Then it checks whether the three rows that is three list has enough and equal column.

  • Step 5 βˆ’ Using the for loop the product value is calculated and stored in the variable named β€œresult”

  • Step 6 βˆ’ The list is initialized with the integer values and three sublists.

  • Step 7 βˆ’ The final output is printed.

Example

#function is defined with two parameters
def product_cols(lst,cols_val):
    #To check whether the input is in the given list
    if not isinstance(lst,list):
        raise Exception(f"object {type(file)} isn't list type")
    
    #if loop is used to check whether all column and indexes are correct
    for a,row in enumerate(lst,start=1):
        try:
            temp=row[cols_val]
        except IndexError:
            raise Exception(f"{str(a)}th given values is not within the limit{str(cols_val)}.")           
              
    # The product is calculated using for loop
    result = 1
    for each_row in lst:
        result *= each_row[cols_val]
        
    return result
#initializing the list element
list1 = [[1, 2, 3], 
           [4, 5, 6], 
           [7, 8, 9]]
#The final output is printed for the elements in index value of 2
print(product_cols(list1, 2))

Output

162

Approach 2: Python Program to product the kth column in lists of lists using the reduce() method

The process may seem to be simple, but implementing the program using the reduce method is tedious. The required modules are imported and depending the input value given the program gets executed.

Algorithm

  • Step 1 βˆ’ The required modules are imported to use the functions like reduce and operator.

  • Step 2 βˆ’ The function is defined with two parameters as the lists of list and the column index value.

  • Step 3 βˆ’ The input is checked, whether it is present in the given list

  • Step 4 βˆ’ Then the rows are checked whether it is properly having all the column elements.

  • Step 5 βˆ’ With the help of reduce function, the product of the lists of lists is calculated and returned using the print() function.

Example

#importing the module to use reduce function
from functools import reduce
#importing the operator
import operator
#defining the function with two parameters
def product_cols(lst,cols_val):
#To check whether the input is in the given list
    if not isinstance(lst,list):
        raise Exception(f"object {type(file)} isn't list type")
    
    #if loop is used to check whether all column and indexes are correct
    for a,row in enumerate(lst,start=1):
        try:
            temp=row[cols_val]
        except IndexError:
            raise Exception(f"{str(a)}the given values is not within the limit{str(cols_val)}.")           
              
    return reduce(operator.mul,[each_row[cols_val] for each_row in lst])
#initializing the list with set of sublists
list1 = [[1, 2, 3], 
           [4, 5, 6], 
           [7, 8, 9]]
#Finally printing the list after the multiplication
print(product_cols(list1, 2))

Output

162

Conclusion

Python comes under the high-level language and the people working with Python can find solutions to the problem using the simple concepts and functionalities. The language is composed of several data structures and from the list is the most common one. The different approaches to print the product of kth column are given using the functools module and for loop method.

Updated on: 04-Sep-2023

46 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements