Sub topic 1
What a list is and how to create one
Prerequisites
This chapter assumes you can already do the following:
- Run a Python script or use the REPL.
- Use the built-in types
int,strandbool, and assign them to variables. - Write
forloops andifstatements. - Call functions and methods, such as
len(x)andtext.upper().
If any of these is unfamiliar, review it first. This chapter introduces lists and their basic properties. Later chapters cover indexing, slicing, methods, copying and performance in detail.
What a list is
A list is Python's built-in ordered, mutable sequence type. Each word in that definition has a specific meaning:
- Ordered means items keep the position you gave them. The first item stays first until you change it.
- Mutable means you can change the list after you create it. You can add, remove and replace items without making a new list.
- Sequence means the list supports
len(), indexing, slicing, iteration and theinoperator, as strings and tuples do.
A list can hold any objects. It stores references to those objects, not copies of them. This detail matters in later chapters on aliasing and nested lists.
mixed = [42, "hello", 3.14, True, [1, 2]]
print(len(mixed)) # 5
print(type(mixed)) # <class 'list'>Items in one list do not need to share a type. In practice, most lists hold items of one kind, such as a list of names or a list of prices. That makes the code that processes them simpler.
Creating lists
Python gives you several ways to create a list. Each suits a different situation.
List literals
A list literal is a comma-separated sequence of values inside square brackets. It is the most common form.
empty = []
primes = [2, 3, 5, 7]
names = ["Ada", "Grace", "Linus"]A trailing comma after the last item is allowed. Many style guides recommend it when each item sits on its own line, because adding an item later changes only one line.
config_files = [
"base.toml",
"dev.toml",
"local.toml",
]
print(len(config_files)) # 3The list() constructor
The list() constructor takes any iterable and builds a new list from its items. An iterable is any object you can loop over, such as a string, a range, a tuple, a set or a dictionary.
print(list("abc")) # ['a', 'b', 'c']
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list((1, 2, 3))) # [1, 2, 3]
print(list({"x": 1, "y": 2})) # ['x', 'y'] (dict keys)
print(list()) # []Two points are easy to miss:
- Calling
list("abc")splits the string into characters. It does not make["abc"]. If you want a one-item list, write the literal. - Iterating over a dictionary yields its keys. Use
list(d.values())orlist(d.items())for the other views.
Because list() always builds a new list, it also works as a way to copy one. Copying is covered in a later chapter.
List comprehensions
A list comprehension builds a list from an iterable in one expression. This chapter shows only the basic form. A later chapter covers it fully.
squares = [n * n for n in range(6) if n % 2 == 0]
print(squares) # [0, 4, 16]Repetition and concatenation
The * operator repeats a list. The + operator joins two lists into a new list.
zeros = [0] * 5
print(zeros) # [0, 0, 0, 0, 0]
combined = [1, 2] + [3, 4]
print(combined) # [1, 2, 3, 4]Repetition is safe for immutable items such as numbers and strings. It is a trap for lists of lists, because the repeated items are references to one object. The nested lists chapter explains this.
Splitting text
Many real lists start as text. The str.split() method returns a list of strings.
line = "red green blue"
colors = line.split()
print(colors) # ['red', 'green', 'blue']
row = "10,20,30"
print(row.split(",")) # ['10', '20', '30']Note that the items are strings. Convert them if you need numbers:
numbers = [int(part) for part in "10,20,30".split(",")]
print(numbers) # [10, 20, 30]The table below summarizes the creation methods.
| Form | Example | Result |
|---|---|---|
| Literal | `[1, 2, 3]` | `[1, 2, 3]` |
| Constructor | `list("hi")` | `['h', 'i']` |
| Range | `list(range(3))` | `[0, 1, 2]` |
| Comprehension | `[n * 2 for n in range(3)]` | `[0, 2, 4]` |
| Repetition | `["x"] * 3` | `['x', 'x', 'x']` |
| Split | `"a b".split()` | `['a', 'b']` |
Basic properties
Length and truthiness
len() returns the number of items. An empty list is falsy and a non-empty list is truthy. The idiomatic emptiness check uses this directly.
tasks = []
if not tasks:
print("Nothing to do") # Nothing to do
tasks = ["write", "test"]
print(len(tasks)) # 2
if tasks:
print("Work remains") # Work remainsPrefer if not tasks: over if len(tasks) == 0:. Both work, but the first is the common Python style.
Membership
The in operator tests whether a value appears in the list. It compares with ==, so equal values match even if they are different objects.
vowels = ["a", "e", "i", "o", "u"]
print("e" in vowels) # True
print("z" not in vowels) # TrueSearching is covered in its own chapter, along with its cost.
Equality and comparison
Two lists are equal when they have the same length and each pair of items at the same position is equal. Order matters.
print([1, 2, 3] == [1, 2, 3]) # True
print([1, 2, 3] == [3, 2, 1]) # False
print([1, 2] < [1, 3]) # True (compared item by item)
print([1, 2] is [1, 2]) # False (two different objects)== compares contents. is compares identity, meaning whether both names refer to the same object. Use == to compare values.
Lists are unhashable
Because lists are mutable, they cannot be dictionary keys or set members. Python raises TypeError if you try.
try:
d = {[1, 2]: "pair"}
except TypeError as err:
print(err) # unhashable type: 'list'If you need a key made of several values, use a tuple instead. A tuple is an immutable sequence, and it is hashable when its items are hashable.
d = {(1, 2): "pair"}
print(d[(1, 2)]) # pairList or tuple?
Lists and tuples look alike, but they signal different intent.
| Property | list | tuple |
|---|---|---|
| Syntax | `[1, 2]` | `(1, 2)` |
| Mutable | Yes | No |
| Hashable | No | Yes, if all items are hashable |
| Typical use | A collection that grows or changes | A fixed record, such as a coordinate |
Use a list for a collection of similar items whose contents or size change. Use a tuple for a small fixed group of values that belong together.
point = (3, 4) # fixed record
scores = [88, 92, 79] # collection that may grow
scores.append(95)
print(scores) # [88, 92, 79, 95]Common creation errors
The list below covers mistakes that appear often when people create lists.
- Using
listas a variable name. Writinglist = [1, 2]hides the built-in, and a laterlist("abc")fails withTypeError: 'list' object is not callable. Use a name such asitems. - Passing several arguments to
list().list(1, 2, 3)raisesTypeError, because the constructor takes at most one iterable. Write[1, 2, 3]orlist((1, 2, 3)). - Passing a non-iterable.
list(5)raisesTypeError: 'int' object is not iterable. Use[5]for a one-item list. - Expecting
split()to convert types. It returns strings only. - Expecting
+to add an item.[1, 2] + 3raisesTypeError, because both operands must be lists. Write[1, 2] + [3], or useappend, which a later chapter covers.
try:
list(5)
except TypeError as err:
print(err) # 'int' object is not iterable
print([1, 2] + [3]) # [1, 2, 3]How lists are stored
You do not need the internals to use lists, but a simple model helps later chapters make sense. CPython, the standard Python implementation, stores a list as a block of memory holding references to its items. The list also keeps a count of used slots and a count of allocated slots. When you add items and the block fills up, Python allocates a larger block and moves the references over.
This model explains three facts you will meet again:
- Reading an item by position is fast, because Python goes straight to that slot.
- Adding at the end is usually cheap, but inserting at the front must shift every other reference.
- A list holds references, so two lists can refer to the same underlying item.
The diagram shows the list ["apple", "banana", "cherry"] as references to separate objects.
Putting it together
The short script below creates a list from text, checks its properties, and shows several of the ideas above.
raw = "3,1,4,1,5"
values = [int(p) for p in raw.split(",")]
print(values) # [3, 1, 4, 1, 5]
print(len(values)) # 5
print(4 in values) # True
print(values == [3, 1, 4, 1, 5]) # True
empty = []
print(bool(empty)) # False
print(bool(values)) # TrueExercise
What does list("hi") == ["hi"] evaluate to, and why? Then write one expression that turns the string "7,8,9" into the list [7, 8, 9] of integers.
Show answer
It evaluates to False. list("hi") iterates over the string and produces the two-item list ['h', 'i'], while ["hi"] is a one-item list. The conversion is [int(p) for p in "7,8,9".split(",")], which splits the text into strings and converts each to an int.
Exercise
Why does {[1, 2]: "a"} raise a TypeError, and what could you use as the key instead?
Show answer
Lists are mutable, so they are unhashable and cannot be dictionary keys. Use a tuple such as (1, 2), which is immutable and hashable when its items are hashable.