Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sum 2D array in Python using map() function
In this tutorial, we are going to find the sum of a 2D array using map() function in Python.
The map() function takes two arguments: function and iterable. It applies the function to every element of the iterable and returns a map object. We can convert the map object into a list or other iterable.
Let's see how to find the sum of a 2D array using the map function ?
Steps to Sum a 2D Array
- Initialize the 2D array using nested lists.
- Pass the sum function and 2D array to the map() function.
- Convert the map object to a list to get row sums.
- Find the total sum using sum() on the result.
Example - Complete Implementation
Here's how to sum all elements in a 2D array using map() ?
# initializing the 2D array
array = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Step 1: Get sum of each row using map()
row_sums = list(map(sum, array))
print("Sum of each row:", row_sums)
# Step 2: Get total sum of all elements
total_sum = sum(row_sums)
print("Total sum of 2D array:", total_sum)
Sum of each row: [6, 15, 24] Total sum of 2D array: 45
How It Works
The map(sum, array) applies the sum() function to each row (sub-list) in the 2D array:
- Row 1: [1, 2, 3] ? sum = 6
- Row 2: [4, 5, 6] ? sum = 15
- Row 3: [7, 8, 9] ? sum = 24
Then sum([6, 15, 24]) gives us the final result: 45.
One-Line Solution
You can combine both steps into a single line ?
array = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Direct sum using map()
total = sum(map(sum, array))
print("Total sum:", total)
Total sum: 45
Conclusion
Using map(sum, array) is an efficient way to sum a 2D array in Python. It first calculates the sum of each row, then sums those results to get the total.
