This Article Will Introduce You to the Use Case of Lists in Python

In this article, you’ll learn how to create a list of lists in python. Lists are very useful when you need a dynamic data structure that can hold multiple items and be easily modified. The list in Pyt …

Updated November 20, 2023

In this article, you’ll learn how to create a list of lists in python. Lists are very useful when you need a dynamic data structure that can hold multiple items and be easily modified. The list in Python is defined by placing all elements inside square brackets “[]”. A list contains elements which can be of any type like string, integer, float etc.

To create a list of lists in python, you just need to place another list as an element in the outer list. Here’s an example:

list_of_lists = [[1,2,3], [4,5,6], [7,8,9]]
print(list_of_lists)
# Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

As you can see, list_of_lists is a list containing three other lists. Each of these inner lists contains three integers, which are all separate entities on their own. This structure lets you manipulate and store data in a very flexible and efficient way.

You can access elements from the inner lists like this:

print(list_of_lists[0][1]) # Output: 2
print(list_of_lists[2][2]) # Output: 9

The first index indicates which list (or row) you’re looking at, and the second index indicates which element within that list (or column) you’re looking at. This makes lists a highly versatile data structure for storing structured data.

You can add elements to a list of lists in the same way as adding elements to any other list: by using the append() or extend() methods, like this:

list_of_lists[0].append(0) # Adds 0 at end of first inner list
print(list_of_lists) # Output: [[1, 2, 3, 0], [4, 5, 6], [7, 8, 9]]

This method modifies the first inner list without changing any other lists or their order.

Finally, as a world-class Python developer, you should know that lists in python are dynamic and can be modified easily. You have the ability to add/remove elements, to change the type of elements (str, int, float etc.), to sort them, and many more features. All these operations ensure that lists are versatile, efficient and suitable for a wide range of use cases.

Hey! Do you love Python? Want to learn more about it?
Let's connect on Twitter or LinkedIn. I talk about this stuff all the time!