loop
Lists in advanced applications

Module 3 · Lists in advanced applications · Lesson 1 of 3

Lists in lists

Nothing says a list's elements have to be simple values. An element can be another list — and that single fact is the key to grids, tables and boards. To reach a value inside a nested list, index twice: people[0] gives you the first inner list, and people[0][0] reaches the first item inside that.

Run it yourselfruns in your browser · Python
main.py

Building these lists by hand — start empty, loop, append — works, but Python has a wonderfully compact alternative made for exactly this: the list comprehension. It builds a whole new list from an old one in a single expression.

[n * n for n in nums]
12345
↓ each one squared
1491625

Read it aloud: “n * n for each n in nums.” One line builds the whole new list.

The shape is always the same: [ expression for item in sequence ]. Take each item, run it through the expression, collect the results. You can even add an if on the end to keep only the items you want.

Run it yourselfruns in your browser · Python
main.py

Comprehensions and nested lists are a natural pair — in the next lesson we use a comprehension to build a whole two-dimensional grid in one line.