Friday, December 27, 2024
Google search engine
HomeLanguagesPython – Kth Column Product in Tuple List

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. 

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

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments