The ultimate guide to “Nested” Lists.
Photo by Abbey Alabi on Unsplash
- Recommended Reading
- Blog Requirements
- What Is a Nested List?
- How to create a nested list.
- How do we print a nested list value?
- Want more information or just a chat?
- Credits
Recommended Reading
Before reading this article, I recommend that you (should) read:
Post Name: Lists
Blog Requirements
Python3
An IDE (See my other blog post for recommendations! — 10 Best Python IDEs for Windows)
What Is a Nested List?
In Python, a nested list is a list that has other lists as its elements. In other words, it’s a list that’s encased in another list. By creating a hierarchical structure, data can be represented in a more organized and structured manner.
How to create a nested list.
First, we shall start with a list named ‘Cars’.
cars = []
Three values will be provided for each car. With a list, we can do this by nesting several lists within the list cars, to make a more “structured” list that we can manipulate further.
Inside the car list, parentheses, we will add an extra parenthesis to make your list look like this:
cars = [
["Mitsibushi","20,000","Red"]
]
Inside the second parentheses, let’s add some values (separated by commas) for the three elements. In this example, we will use ‘Car Make’, ‘Price’, and ‘Colour’.
cars = [
["Mitsibushi","20,000","Red"]
]
We will then add a second car by placing a comma after the 1st parenthesis of closure and then write a second nested list:
cars = [
["Mitsibushi","20,000","Red"],
["Toyota","30,000","Blue"]
]
Here’s our first nested list!
How do we print a nested list value?
This depends on what you would like as a result. If you want a full list to be printed, you could write:
print(cars)
If you would like a specific list, such as the Toyota list. You could write:
print(cars[1])
Take note of how the list indexing begins at 0!
Let’s say you only wanted the price of the Toyota…
If you have a nested list, it’s easy too. All you have to do is provide a second index value to the print command.
print(cars[1][1])
Data structures like matrices, tables, hierarchical data, or multi-dimensional arrays are often represented by nested lists. They offer a flexible method for arranging and working with complex data relationships.
Want more information or just a chat?
You can find me on Twitter, Facebook, and LinkedIn or send me an email!
Credits
Icons made by Freepik www.flaticon.com
I like my titles to be tidy.
I also like my grammar and spelling to be in check.