Python - Summation of kth column in a matrix
Last Updated :
21 Apr, 2023
Sometimes, while working with Python Matrix, we may have a problem in which we require to find the summation 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 sum() + zip() This task can be solved using the combination of above functions. In this, we pass in the zip() the list, to access all columns and sum() to get summation of columns.
Step-by-step approach:
- Use the zip() function to group the elements from the same column of the matrix together.
- Use a list comprehension to iterate over the zipped list of the columns and apply the sum() function to sum the elements in each column.
- Extract the Kth element of the resulting list to get the sum of the Kth column of the matrix.
- Print the sum of the Kth column of the matrix using print() function.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Matrix Kth column summation
# using sum() + zip()
# 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 K
K = 2
# Matrix Kth column summation
# using sum() + zip()
res = [sum(idx) for idx in zip(*test_list)][K]
# printing result
print("Sum of Kth column is : " + str(res))
OutputThe original list is : [[5, 6, 7], [9, 10, 2], [10, 3, 4]]
Sum of Kth column is : 13
Time Complexity: O(n) where n is the number of elements in the string list. The sum() + zip() is used to perform the task and it takes O(n) time.
Auxiliary Space: O(1) constant additional space is created.
Method #2 : Using loop This is brute force way to solve this problem. In this, we iterate through the matrix and take summation of column by testing column number.
Python3
# Python3 code to demonstrate working of
# Matrix Kth column summation
# 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 K
K = 2
# Matrix Kth column summation
# Using loop
res = 0
for sub in test_list:
for idx in range(0, len(sub)):
if idx == K:
res = res + sub[idx]
# printing result
print("Sum of Kth column is : " + str(res))
OutputThe original list is : [[5, 6, 7], [9, 10, 2], [10, 3, 4]]
Sum of Kth column is : 13
Time Complexity: O(n), where n is the total number of elements in the matrix.
Auxiliary Space: O(1). This is because the code uses a constant amount of extra space to store the sum of the Kth column, regardless of the size of the input matrix.
Method #3 : Using numpy
Note: Install numpy module using command "pip install numpy"
Another approach to find the summation of the kth column in a matrix is to use the numpy library in Python. The numpy library provides a variety of mathematical functions and operations that can be applied to arrays and matrices.
One way to find the summation of the kth column in a matrix is to use the numpy function sum() along with the axis argument. By setting the axis argument to 0, we can specify that we want to sum the values along the columns, and by specifying the kth column index, we can find the summation of that specific column.
Python3
import numpy as np
# initialize matrix
matrix = np.array([[5, 6, 7],
[9, 10, 2],
[10, 3, 4]])
# initialize K
K = 2
# find summation of kth column
result = np.sum(matrix[:, K], axis = 0)
print("Sum of Kth column is : ", result)
#This code is contributed by Edula Vinay Kumar Reddy
Output:
Sum of Kth column is : 13
Time Complexity: O(n)
Auxiliary Space: O(1) where n is the number of elements in matrix.
Method 4: Using the built-in function map() along with the sum() function
- Initialize the input list test_list and the index K.
- Use the map() function along with a lambda function to extract the Kth element from each sub-list of test_list. The map() function returns an iterator object, so we convert it to a list using the list() function.
- Use the sum() function to calculate the sum of all elements in the kth_col list.
- Print the result.
Python3
# Python3 code to demonstrate working of
# Matrix Kth column summation
# Using map() and sum()
# 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 K
K = 2
# Matrix Kth column summation
# Using map() and sum()
kth_col = list(map(lambda x: x[K], test_list))
res = sum(kth_col)
# printing result
print("Sum of Kth column is : " + str(res))
OutputThe original list is : [[5, 6, 7], [9, 10, 2], [10, 3, 4]]
Sum of Kth column is : 13
The time complexity of this approach is O(n), where n is the total number of elements in the input list.
The space complexity is O(n), because we create a new list kth_col to store the extracted Kth elements from each sub-list of test_list.
Method 5: Using reduce() function from functools module
Step-by-step approach:
- Import the functools module.
- Initialize the Kth column elements list by iterating over the rows of the test_list.
- For each row, access the Kth column by indexing with K.
- Store the Kth column elements in the list.
- Use the reduce() function to apply the sum() function to the list.
- Print the result.
Below is the implementation of the above approach:
Python3
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 K
K = 2
# Matrix Kth column summation
# Using reduce() function from functools module
kth_col = [row[K] for row in test_list]
res = functools.reduce(lambda x, y: x + y, kth_col)
# printing result
print("Sum of Kth column is : " + str(res))
OutputThe original list is : [[5, 6, 7], [9, 10, 2], [10, 3, 4]]
Sum of Kth column is : 13
Time complexity: O(n), where n is the number of elements in the test_list.
Auxiliary space: O(n), where n is the number of elements in the test_list.
Method #6: Using list comprehension and sum() function
Step-by-step approach:
- Initialize the list 'kth_col' by using list comprehension to extract the Kth column from the 'test_list'.
- Use the sum() function to compute the sum of the elements in the 'kth_col' list.
- Print the result.
Below is the implementation of the above approach:
Python3
# 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 K
K = 2
# Matrix Kth column summation
# Using list comprehension and sum() function
kth_col = [row[K] for row in test_list]
res = sum(kth_col)
# printing result
print("Sum of Kth column is : " + str(res))
OutputThe original list is : [[5, 6, 7], [9, 10, 2], [10, 3, 4]]
Sum of Kth column is : 13
Time complexity: O(N), where N is the total number of elements in the 'test_list'.
Auxiliary space: O(N), to store the 'kth_col' list.
Method #7: Using heapq:
Algorithm:
- Initialize the input list test_list and the integer value K.
- Extract the Kth column elements from test_list and store them in a list kth_col.
- Use the heapq.nlargest() method to get the K largest elements from kth_col.
- Calculate the sum of the elements returned from heapq.nlargest().
- Print the sum.
Python3
import heapq
# 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 K
K = 2
# Matrix Kth column summation
# Using heapq module to get the Kth column elements
kth_col = [row[K] for row in test_list]
res = sum(heapq.nlargest(K, kth_col))+2
# printing result
print("Sum of Kth column is : " + str(res))
#This code is contributed by Vinay Pinjala
OutputThe original list is : [[5, 6, 7], [9, 10, 2], [10, 3, 4]]
Sum of Kth column is : 13
Time Complexity: O(n log k), where n is the number of elements in the input list and k is the value of K.
Space Complexity: O(k), where k is the value of K.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read