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

Kursusindhold

Introduction to Python (dev copy)

Introduction to Python (dev copy)

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

book
Nested Lists in Python

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

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 4. Kapitel 4
Vi beklager, at noget gik galt. Hvad skete der?
some-alt