Python – Column wise sum of nested list
Published: 2024-03-13 08:21:29

Title : [Python – Column wise sum of nested list](https://pythonkb.com/python-column-wise-sum-of-nested-list/)

### Introduction:
In Python, we often work with nested lists where each sublist represents a row or a record, and the elements within each sublist represent columns or attributes. One common operation is to compute the column-wise sum of such nested lists. This means adding up the elements in each column across all rows. 

### Approach:
We will write a Python function that takes a nested list as input and returns a list containing the sum of elements in each column. To achieve this, we'll iterate through each row of the nested list and add corresponding elements to the sum of each column. We'll use a loop to traverse the nested list and another loop to traverse each sublist.

Let's dive into the code with explanations:

```python
def column_wise_sum(nested_list):
    num_cols = len(nested_list[0])  # Number of columns is determined by the length of the first sublist
    col_sum = [0] * num_cols  # Initialize a list to hold column sums, filled with zeros initially

    for row in nested_list:  # Iterate through each row in the nested list
        for i in range(num_cols):  # Iterate through each element in the row
            col_sum[i] += row[i]  # Add the element to the corresponding column sum

    return col_sum
```

### Explanation:
1. **`column_wise_sum` Function**: This is the main function that computes the column-wise sum of the nested list.
   
2. **`num_cols` Calculation**: We determine the number of columns by finding the length of the first sublist in the nested list. This assumes that all sublists have the same number of elements.

3. **`col_sum` Initialization**: We initialize a list called `col_sum` to store the sum of elements for each column. This list is initialized with zeros and its length is equal to the number of columns.

4. **Nested Loop**: We use nested loops to traverse the nested list. The outer loop iterates through each sublist (row) in the nested list, while the inner loop iterates through each element in the sublist.

5. **Updating Column Sums**: Inside the inner loop, we add the current element to the corresponding column sum. We use the index `i` to access the correct column in `col_sum`.

6. **Return**: Finally, we return the `col_sum` list containing the sum of elements for each column.

### Examples:
Let's see some examples to understand how the function works:

#### Example 1:
```python
nested_list = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(column_wise_sum(nested_list))
```
**Output:**
```
[12, 15, 18]
```
Explanation: The sums of the columns are [1+4+7, 2+5+8, 3+6+9] = [12, 15, 18].

#### Example 2:
```python
nested_list = [
    [1, 2],
    [3, 4],
    [5, 6]
]

print(column_wise_sum(nested_list))
```
**Output:**
```
[9, 12]
```
Explanation: The sums of the columns are [1+3+5, 2+4+6] = [9, 12].

#### Example 3:
```python
nested_list = [
    [1, 2, 3],
    [4, 5, 6]
]

print(column_wise_sum(nested_list))
```
**Output:**
```
[5, 7, 9]
```
Explanation: The sums of the columns are [1+4, 2+5, 3+6] = [5, 7, 9].

#### Example 4:
```python
nested_list = [
    [1],
    [2],
    [3]
]

print(column_wise_sum(nested_list))
```
**Output:**
```
[6]
```
Explanation: The sums of the columns are [1+2+3] = [6].

#### Example 5:
```python
nested_list = [
    [1, 2, 3, 4],
    [5, 6, 7, 8]
]

print(column_wise_sum(nested_list))
```
**Output:**
```
[6, 8, 10, 12]
```
Explanation: The sums of the columns are [1+5, 2+6, 3+7, 4+8] = [6, 8, 10, 12].

### Conclusion:
In this explanation, we have provided a Python function to compute the column-wise sum of a nested list, along with detailed explanations of each part of the code. We have also provided examples and their corresponding outputs to demonstrate the functionality of the function.