 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Kth Column Product in Tuple List in Python
When it is required to find the 'K'th column product in a list of tuple, a simple list comprehension and a loop can be used.
A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error. They are important contains since they ensure read-only access. A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
A list of tuple basically contains tuples enclosed in a list.
The list comprehension is a shorthand to iterate through the list and perform operations on it.
Below is a demonstration of the same −
Example
def prod_compute(my_val) :    my_result = 1    for elem in my_val:       my_result *= elem    return my_result my_list = [(51, 62, 75), (18,39, 25), (81, 19, 99)] print("The list is : " ) print(my_list) print("The value of 'K' has been initialized") K = 2 my_result = prod_compute([sub[K] for sub in my_list]) print("The product of the 'K'th Column of the list of tuples is : ") print(my_result)  Output
The list is : [(51, 62, 75), (18, 39, 25), (81, 19, 99)] The value of 'K' has been initialized The product of the 'K'th Column of the list of tuples is : 185625
Explanation
- A function named 'prod_compute' is defined, that takes one parameter.
- A variable is initialized to 1, and the parameter is iterated over.
- This element is multiplied with the variable.
- It is returned as the output.
- A list of tuples is defined, and is displayed on the console.
- The function is called by passing this list of tuple.
- The output is displayed on the console.
Advertisements
 