Lists
Learn about the details of the lists, along with a few of their useful properties in Python.
We'll cover the following
Overview
Python’s generic list structure is integrated into a number of language features. We don’t need to import them and rarely need to use method syntax to access their features. We can visit all the items in a list without explicitly requesting an iterator object, and we can construct a list (as with a dictionary) with very simple-looking syntax.
In Python, lists should normally be used when we want to store several instances of the same type of object; lists of strings or lists of numbers. We’ll often use a type hint list[T]
to specify the type, T
, of an object kept in the list, for example, list[int]
or list[str]
.
Note: Remember that
from __future__ import annotations
is required for this to work.
Mutability
Lists must be used when we want to store items in some kind of order. Often, this is the order in which they were inserted, but other criteria can also sort them. Lists are mutable, so items can be added, replaced, and removed from the list. This can be handy for reflecting the state of some more complex objects.
Like dictionaries, Python lists use an extremely efficient and well-tuned internal data structure, so we can worry about what we’re storing rather than how we’re storing it. Python expands on lists to provide some specialized data structures for queues and stacks. Python doesn’t make a distinction between lists based on arrays or lists that use links. Generally, the built-in list data structure can serve a wide variety of purposes.
Lists: Best suitability
Don’t use lists for collecting different attributes of individual items. Tuples, named tuples, dictionaries, and objects would all be more suitable for collecting different kinds of attribute values. In the previous lessons, our first Stock
data examples stored the current, minimum, and maximum prices, each a different attribute with a distinct meaning in a single sequence. This isn’t really ideal, and named tuples or dataclasses were clearly superior.
Example
Here’s a convoluted counter example demonstrating how we could perform the frequency example using a list. It is much more complicated than the dictionary examples and illustrates the effect that choosing the right (or wrong) data structure can have on the readability (and performance) of our code. This is demonstrated as follows:
Get hands-on with 1200+ tech skills courses.