Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Nested Lists
course content

Course Content

Introduction to Python

Nested ListsNested Lists

As mentioned in the opening chapter, lists in Python can store various data types, even including other lists. What's unique about Python, compared to many other programming languages, is that these nested lists can differ in length. Let's dive into an example. Imagine we have data about countries and their respective areas. Instead of jamming all that information into a single list, it would be more organized to have a distinct list for each country.

As illustrated, every country has its dedicated list nested within the primary list. Now, you might wonder, how do we navigate through such a structure? If we're dealing with a two-dimensional list, its elements are also lists. And, we can access the inner list's items using indexing. Consider a two-dimensional list named countries_2d that contains 3 main elements (which are lists). Each of these lists has 2 items. So, countries_2d[1] fetches the second list in the main list (keep in mind, Python indexing begins at 0). Moreover, countries_2d[1][0] retrieves the first item within that second list. Check out the example below for clarity.

Everything was clear?

Section 4. Chapter 4