How To Add List Of List In Python

In this tutorial, we will learn how to add a list of lists in Python. This task is commonly encountered in many programming scenarios, especially when working with matrices or 2D arrays, where the addition of elements can be used to perform calculations. We will walk through a step-by-step process to understand how this is done in Python.

Step 1: Creating the List of Lists

In Python, you can create a list of lists by simply placing a list inside another list. Let’s create two lists of lists that will be used for this tutorial. Below is an example:

Now we have two list of lists named list1 and list2, each containing 3 rows and 3 columns of integer elements.

Step 2: Adding the List of Lists

To add two list of lists, you must iterate through each list and add the corresponding elements. To do this we will use nested loops. The outer loop will iterate through each row while the inner loop will iterate through each column within that row. Here’s the code:

In the code snippet above, the row list is a temporary placeholder for the addition of the elements in the current row for both list1 and list2. The row.append(list1[i][j] + list2[i][j]) line adds the corresponding elements from list1 and list2 and appends the result to the row list. After that, the row list is appended to the result list.

Step 3: Using List Comprehensions

Python provides a more concise way to write code using list comprehensions. Instead of using nested loops like in the previous step, you can achieve the same result using the following single line of code:

This single line of code is equivalent to the nested loops in Step 2 but is more compact and easier to read.

Now let’s see the full code in action, using both the nested loop approach and the list comprehension approach.

The output of the above code should be:

Result using nested loops: [[10, 10, 10], [10, 10, 10], [10, 10, 10]]
Result using list comprehensions: [[10, 10, 10], [10, 10, 10], [10, 10, 10]]

Conclusion

Now you have learned how to add a list of lists in Python using both the nested loop approach and the list comprehension approach.

Both methods will provide the same result, but the list comprehension approach is more concise.

Debating which method to use depends on your personal preference and the readability of your code.