How To Make A List Of Lists In Python

In this tutorial, we will learn how to make a list of lists in Python. A list of lists is simply a collection of lists, often known as a 2D list. This data structure is similar to a matrix, where elements are organized in rows and columns.

The concept of a list of lists is very useful in scenarios like working with a grid or a spreadsheet. In Python, a list of lists can be created and manipulated using a combination of built-in functions and list comprehension.

Step 1: Create a list of lists

There are a couple of approaches to creating a list of lists in Python. Here, we are going to demonstrate the two most common methods.

1. Using built-in functions

The output:

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

In this method, we first create an empty list named list_of_lists. We then loop through the number of rows (3 in this example) and create a new empty list named inner_list in each iteration. In the nested loop, we iterate through the number of columns (4 in this example) and append a value (0 in this case) to inner_list. After completing the inner loop, we append inner_list to list_of_lists.

2. Using list comprehension

The output:

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

In this method, we use list comprehension to create a list of lists in a single line of code. It is a concise and efficient way to create and initialize a list of lists, especially when the dimensions are known in advance.

Step 2: Accessing elements of a list of lists

You can access elements of a list of lists by using the row and column indices, as demonstrated below:

The output:

6

In this example, you can see that we accessed the element at row 1 and column 2 (zero-indexed) from the list_of_lists. The accessed element is 6.

Step 3: Modifying elements of a list of lists

You can modify the elements of a list of lists by assigning a new value to the specified row and column indices, as shown below:

The output:

[[1, 2, 3], [4, 5, 10], [7, 8, 9]]

In this example, we modified the element at row 1 and column 2 (zero-indexed) of the list_of_lists. The new value is 10, and the updated list_of_lists is printed.

Full code

Conclusion

In this tutorial, we learned how to create, access, and modify a list of lists (2D lists) in Python using built-in functions and list comprehension. A list of lists can be a powerful data structure for handling complex data in grids, spreadsheets, or matrices.