Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Nested Lists | Other Data Types
Introduction to Python
course content

Course Content

Introduction to Python

Introduction to Python

1. First Acquaintance
2. Variables and Types
3. Conditional Statements
4. Other Data Types
5. Loops
6. Functions

bookNested 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.

123
# Two-dimensional list countries_2d = [["USA", 9629091], ["Canada", 9984670], ["Germany", 357114]] print(countries_2d)
copy

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.

123456
# Two-dimensional list countries_2d = [['USA', 9629091], ['Canada', 9984670], ['Germany', 357114]] # Pull elements print(countries_2d[1]) print(countries_2d[1][0])
copy

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 4
some-alt