course content

Course Content

Introduction to Python

Nested ListsNested Lists

As stated in the first chapter, we can save values of different types in lists; that is, we can save lists inside lists. Unlike many programming languages, nested lists can be of different lengths in Python.

Let's consider another example. We have information about countries and their areas. Storing them in one list is not convenient. Therefore each country will have a separate list.

As you can see above, each country has its "own" list within the larger list. How do we access elements in such a structure? If the list is two-dimensional, then its elements are lists whose elements can be accessed by indexing them.

For example, the two-dimensional list countries_2d consists of 3 elements (these are lists), each of which consists of 2 elements. This means that countries_2d[1] will return the second element of the entire list (remember, indexing in Python starts from 0), and countries_2d[1][0] will return the first element of the sub-list. Take a look at the example below.

Section 4.

Chapter 4