Open In App

Python – Kth Column Product in Tuple List

Last Updated : 11 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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. 

Method #1: Using list comprehension + loop 

This task can be performed using the combination of above functionalities. In this, product of index occurs using explicit product function and list comprehension drives the iteration and access of Kth index element of each tuple in list. 

Python3




# Python3 code to demonstrate working of
# Tuple List Kth Column Product
# using list comprehension + loop
 
# getting Product
 
 
def prod(val):
    res = 1
    for ele in val:
        res *= ele
    return res
 
 
# initialize list
test_list = [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize K
K = 2
 
# Tuple List Kth Column Product
# using list comprehension + loop
res = prod([sub[K] for sub in test_list])
 
# printing result
print("Product of Kth Column of Tuple List : " + str(res))


Output : 

The original list is : [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
Product of Kth Column of Tuple List : 665

The time complexity of the above code is O(n), where n is the number of tuples in the list. 
The Auxiliary space of the code is O(1), as it only uses constant extra space to store intermediate variables.

Method #2 : Using imap() + loop + itemgetter() 

The combination of above functions can also achieve this task. This approach is generator based and recommended in case we have a very large list. In this, product function is used to perform product, itemgetter to get Kth index and imap() performs the task of mapping elements to extract product. Works only in Python2. 

Python




# Python code to demonstrate working of
# Tuple List Kth Column Product
# using imap() + loop + itemgetter()
from operator import itemgetter
from itertools import imap
 
# getting Product
 
 
def prod(val):
    res = 1
    for ele in val:
        res *= ele
    return res
 
 
# initialize list
test_list = [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize K
K = 2
 
# Tuple List Kth Column Product
# using imap() + loop + itemgetter()
idx = itemgetter(K)
res = prod(imap(idx, test_list))
 
# printing result
print("Product of Kth Column of Tuple List : " + str(res))


Output : 

The original list is : [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
Product of Kth Column of Tuple List : 665

Time complexity: O(n), where n is the number of tuples in the list.

Auxiliary space: O(1), since the code only uses a constant amount of extra space to store variables such as res and K. 

Method #3: Using functors.reduce() and operator.mul

Python3




# Python3 code to demonstrate working of
# Tuple List Kth Column Product
 
# initialize list
test_list = [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize K
K = 2
 
# Tuple List Kth Column Product
x=[]
for i in test_list:
    x.append(i[K])
 
from functools import reduce
import operator
 
res=reduce(operator.mul, x , 1)
# printing result
print("Product of Kth Column of Tuple List : " + str(res))


Output

The original list is : [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
Product of Kth Column of Tuple List : 665

Time complexity of the given code is O(n), where n is the number of tuples in the list. 

The auxiliary space used by the code is O(n), where n is the number of tuples in the list. 

Method #4: Using numpy.prod()

This approach uses the numpy library’s prod() function to calculate the product of all elements in the specified column (Kth index) of the tuple list. It is a more concise and efficient method, as it eliminates the need for explicit loops or list comprehension.

Python3




import numpy as np
 
# initialize list
test_list = [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize K
K = 2
 
# Tuple List Kth Column Product
column = [i[K] for i in test_list]
res = np.prod(column)
 
# printing result
print("Product of Kth Column of Tuple List : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output:

The original list is : [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
Product of Kth Column of Tuple List : 665

Time complexity: O(n)
Auxiliary space: O(n)

Method #5: Using a loop without numpy

We can calculate the product of the Kth column of a list of tuples, where the value of K is provided as an input. It iterates over the list of tuples, extracts the Kth element of each tuple, and multiplies them together to get the product

Python3




test_list = [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
K = 2
 
product = 1
for tup in test_list:
    product *= tup[K]
 
print("Product of Kth Column of Tuple List: " + str(product))


Output

Product of Kth Column of Tuple List: 665

The time complexity of this implementation is O(n), where n is the number of tuples in the list.

 The space complexity is O(1), because we only need to store a few variables in memory.

Method #6: Using functools.reduce() and lambda function

  1. Import functools module
  2. Initialize K
  3. Define a lambda function that takes two arguments and returns their product
  4. Use map() to extract the Kth element from each tuple and create a generator object
  5. Use functools.reduce() with the lambda function to find the product of the generator object
  6. Assign the result to res

Python3




import functools
 
# initialize list
test_list = [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize K
K = 2
 
# Tuple List Kth Column Product using functools.reduce() and lambda function
res = functools.reduce(lambda x, y: x*y, map(lambda x: x[K], test_list))
 
# printing result
print("Product of Kth Column of Tuple List : " + str(res))


Output

The original list is : [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
Product of Kth Column of Tuple List : 665

Time complexity: O(n), where n is the number of tuples in test_list
Auxiliary space: O(1)

Method #7: Using pandas
This approach uses the panda. The given list of tuples is first converted to a pandas DataFrame using the pd.DataFrame() method. Then, the Kth column is selected using the .iloc[:, K] syntax, where all rows are selected and K denotes the column index. The prod() method is used to find the product of values in the Kth column. Then, the result is printed.

Python3




import pandas as pd
 
# initialize list
test_list = [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
 
# convert list to pandas dataframe
df = pd.DataFrame(test_list)
 
# initialize K
K = 2
 
# calculate product of Kth column
product = df.iloc[:, K].prod()
 
# print result
print("Product of Kth Column of Tuple List : " + str(product))


Output:

Product of Kth Column of Tuple List : 665

Time complexity: O(n), where n is the number of tuples in input list
Auxiliary space: O(n), where n is the number of tuples in input list



Next Article

Similar Reads

Python - Consecutive Kth column Difference 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 absolute difference 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. Examples: Input : test_list = [(5, 4, 2
6 min read
Python | Summation of Kth Column of 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 possible accumulation of its Kth index. This problem has applications in the web development domain while working with data information. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehensio
7 min read
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 : Using loop + zip() This task can be solved using the c
4 min read
Python | Cumulative Nested Tuple Column Product
Sometimes, while working with records, we can have a problem in which we require to perform index wise multiplication of tuple elements. This can get complicated with tuple elements to be tuple and inner elements again be tuple. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using zip() + nested generator expression The
7 min read
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 : Using zip() + list comprehension This problem ca
4 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python Program to find tuple indices from other tuple list
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples. Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]Output : [3, 1]Explanation : (3, 4) from search list is found on 3rd index on test_list, hence included in r
8 min read
Python Program to Merge tuple list by overlapping mid tuple
Given two lists that contain tuples as elements, the task is to write a Python program to accommodate tuples from the second list between consecutive tuples from the first list, after considering ranges present between both the consecutive tuples from the first list. Input : test_list1 = [(4, 8), (19, 22), (28, 30), (31, 50)], test_list2 = [(10, 12
11 min read
three90RightbarBannerImg