A list of lists
You already know that a list stores multiple items in a single variable:
grocery_list = ["Eggs", "Milk", "Waffles"]
Here is the twist: the items in a list do not have to be strings or numbers. A list can hold other lists. Suppose our grocery shopper buys food from several different stores. Instead of one giant jumbled list, they can make a list where each item is itself a little list: the store's name, followed by what to buy there:
grocery_list_enhanced = [ ["Butchers Shop", "Meat", "Cheese", "Olives"], ["Bakery", "Bread", "Coffee Beans", "Cinnamon Buns"], ["Pizzeria", "Dough"] ]
Each inner list is one single item of grocery_list_enhanced, and each inner list has its own set of items. When lists are stored inside a list like this, we call it a 2D list (two-dimensional list).
Nothing new to memorize: a 2D list has the exact same rules as a regular list. Indexes still start at 0, and square brackets still grab items. The only difference is what is inside: the items happen to be lists too.
Double indexing: two brackets, two steps
Since a 2D list is still a list, one index grabs one item. But now that item is a whole list. Index 0 is the entire Butchers Shop list:
butcher = grocery_list_enhanced[0] print(butcher)
['Butchers Shop', 'Meat', 'Cheese', 'Olives']
To reach an item inside that inner list, index into it a second time. butcher is just a normal list, so butcher[2] is its third item:
butcher = grocery_list_enhanced[0] cheese = butcher[2] print(cheese)
Cheese
Storing the inner list in its own variable works, but there is a shortcut. Stack both indexes into one call with two sets of brackets:
cheese = grocery_list_enhanced[0][2] print(cheese)
Cheese
Read it left to right: the first index (0) picks which inner list, and the second index (2) picks which item inside it. The general format is always:
my_2d_list[which list][which item in that list] First bracket: the outer list. Second bracket: inside the inner list.
Practice: the bookstore
Lost in the Stacks
A bookstore stores its books in a 2D list. Each inner list holds one book's name and author, in that order. The staff is having trouble finding information. Help them out:
- Print the author of The Autobiography of Malcolm X.
- Print the book written by the author Dan Brown.
book_list = [["Siddartha", "Herman Hesse"], ["The Da Vinci Code", "Dan Brown"], ["The Autobiography of Malcolm X", "Alex Haley"]] # print out the author of The Autobiography of Malcolm X # print out the book written by Dan Brown
book_list = [["Siddartha", "Herman Hesse"], ["The Da Vinci Code", "Dan Brown"], ["The Autobiography of Malcolm X", "Alex Haley"]] # Malcolm X's book is the THIRD inner list (index 2). # The author is the SECOND item inside it (index 1). print(book_list[2][1]) # Dan Brown's book is the SECOND inner list (index 1). # The book name is the FIRST item inside it (index 0). print(book_list[1][0])
Alex Haley The Da Vinci Code
Notice the pattern: first bracket finds the right book, second bracket finds the right piece of information about that book.
Rows and columns
Why "2D"? Because a list of lists can stand in for two-dimensional things in the real world. Instead of picturing lists inside lists, picture a grid. Here is a tic-tac-toe board:
tic_tac_toe = [ ["X", "O", "X"], ["-", "-", "-"], ["O", "X", "X"] ]
Written across multiple lines, the shape jumps out at you. Each inner list is a row of the board, and each position inside a row is a column:
Now double indexing has a super clear meaning. To grab any square of the board, give its row first, then its column:
tic_tac_toe[row][column] Row first, column second. Always. Down before across.
Changing a cell
Changing a value works exactly like changing an item in a regular list: point at the cell with both indexes and assign something new. The middle row of our board is empty, so let O take the center square:
tic_tac_toe = [ ["X", "O", "X"], ["-", "-", "-"], ["O", "X", "X"] ] tic_tac_toe[1][1] = "O" # row 1, column 1: the center print(tic_tac_toe[1])
['-', 'O', '-']
The #1 mistake with 2D lists: swapping row and column. grid[2][0] and grid[0][2] are different cells, and on a non-square grid the swapped version can even crash with an IndexError. Try it yourself in the explorer below.
Grid explorer
Time to fire some coordinates. Below is a real 2D list called grid: a tiny battleship board with 3 rows and 4 columns. "~" is water and "S" is a ship. Click any cell, or type a row and column, and see the exact Python that reaches it. Then change a cell, fire a swapped shot, and let the nested loop sweep the whole board.
Grid explorer
grid : 3 rows × 4 columnsLook up a cell
Row first, then column. Or just click a cell.
Change it
Assigns a new value to that same cell.
The classic mistake
Fires grid[col][row] with your numbers swapped.
for row in grid: for item in row: print(item)
Nested for loops: visiting every cell
To print or search every value in a 2D list, one loop is not enough. You need nested loops (a loop inside a loop):
- The outer loop goes through the 2D list one row at a time.
- The inner loop goes through that row one item at a time.
tic_tac_toe = [ ["X", "O", "X"], ["-", "-", "-"], ["O", "X", "X"] ] for row in tic_tac_toe: for item in row: print(item)
X O X - - - O X X
Follow the order of the output: the whole first row prints before the second row starts, like reading a page word by word, line by line. The same nested structure is how you search a 2D list for a specific value, which is exactly what the next practice problem asks you to do.
Practice: is it in stock?
Bookstore Stock Checker
The bookstore is back! They want a program that tells the cashier whether a certain book is in stock. The cashier types in a book name, and the program prints True if it is in book_list and False if it is not. Build it with a nested for loop.
book_list = [["Siddartha", "Herman Hesse"], ["The Da Vinci Code", "Dan Brown"], ["The Autobiography of Malcolm X", "Alex Haley"]] # book stores the value entered by the cashier book = input("Enter a book: ") # create a program that prints True if a book is in the book_list # and False if the book is not in the book_list
book_list = [["Siddartha", "Herman Hesse"], ["The Da Vinci Code", "Dan Brown"], ["The Autobiography of Malcolm X", "Alex Haley"]] book = input("Enter a book: ") # Start by assuming it is NOT in stock in_stock = False # Outer loop: check each inner list (each book entry) for entry in book_list: # Inner loop: check each item in that entry for item in entry: if item == book: in_stock = True print(in_stock)
Enter a book: The Da Vinci Code True
The flag pattern: start in_stock at False, and only flip it to True if the loop finds a match. If nothing matches, it stays False. You will use this trick constantly.
Where grids show up
Once you can see grids, you will spot 2D lists everywhere:
- Game boards. Tic-tac-toe, battleship, chess, Minesweeper: every square of the board is one cell of a 2D list.
- Seating charts. A classroom is rows of desks. seats[2][4] is the student in row 2, seat 4.
- Pixel grids. A digital image is a giant grid of pixels. Editing a photo means changing values in a huge 2D list, one image[row][col] at a time.
Think you have the hang of grids? Prove it on the quiz.
Quick quiz
1. If board = [["a", "b", "c"], ["d", "e", "f"]], what does print(board[1][0]) print?
2. Which code prints every value in a 2D list called grid?
3. Which statement puts "X" in row 0, column 2 of board?
Keep learning Python
You can now build and navigate a whole grid of data. Brush up on regular lists if double indexing still feels shaky, or level up your loops so your nested sweeps get even more powerful.