liveBook · Manning

List

As explained in A Pythonic Adventure: From Python basics to a working web app

A Python list is an ordered, mutable collection that can contain values of different types, including other lists.

A Python list collects related items under one name. Put items inside square brackets and separate them with commas. A menu can use one list for drinks, another for flavors, and another for toppings. Lists can hold strings, numbers, or a mixture of both; they can also contain other lists. section 2.0 section 2.1

drinks = ["chocolate", "coffee", "decaf"]
flavors = ["caramel", "vanilla", "peppermint", "raspberry", "plain"]
toppings = ["chocolate", "cinnamon", "caramel"]

These three lists give a coffee shop program a small, editable menu to work with. section 2.0

A list becomes useful when the program needs to work through or choose from its items:

  • Use a for loop to print each item on its own line instead of printing the whole list in Python’s bracketed display. section 2.0
  • Keep a counter while looping when people need numbered menu choices. section 2.0
  • Retrieve an item with its list index in square brackets, such as drinks[0]. section 2.0 section 2.1
  • Remember that list indices start at 0, even when a menu shown to a customer starts numbering at 1. section 2.0 section 2.1

Turn a menu choice into a list lookup

input() returns a string, so it cannot be used directly as a list index. Convert the choice with int(), then subtract 1 when the displayed menu begins at 1. For example, drinks[int(drink) - 1] finds the first displayed drink when the customer enters 1. This links friendly menu numbering to Python’s zero-based indexing. section 2.0

Lists can also gather records. Start with an empty list using orders = [], then add order dictionaries with append(). The resulting list can be saved as structured JSON data, allowing several coffee-shop orders to travel together in one file. section 8.0

How A Pythonic Adventure: From Python basics to a working web app covers it

How deep it goes
Defines lists and zero-based indices, then works through looping, input conversion, retrieval, and append usage without storage internals.
Examples
Demonstrates drinks, flavors, and toppings menus, numbered selections, and a list of order dictionaries.
What it assumes
Introduces list items and indices while distinguishing strings from numbers returned by keyboard input.
What you can do after
Apply it via Python to create menus, print their items, and retrieve selections by converted numeric index.
How it connects
Connects lists with for loops, strings, numbers, input(), int(), dictionaries, JSON, and append().

Also explained in

Compare how 21 books explain list →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of A Pythonic Adventure: From Python basics to a working web app. The section links point to the parts of the book it draws on.