Sub topic 1
What a List Is and How to Create One
Prerequisites
This chapter assumes you can run a Python script or use the REPL (the interactive prompt). You should know the built-in types int, str and bool, and you should be able to write a for loop and an if statement. You should also be comfortable calling functions and methods.
What a list is
A list is Python's built-in ordered, mutable sequence type. Each part of that definition has a practical meaning:
- Ordered: items keep the position you gave them. The first item stays first until you change it.
- Mutable: you can change a list after you create it. You can add, remove and replace items without making a new list.
- Sequence: items sit one after another, and each has a numeric position called an index. Indexes start at 0.
A list can hold any objects. It can also mix types, and it can hold duplicates.
Creating lists
The most common way is a list literal: items separated by commas inside square brackets.
fruits = ["apple", "banana", "cherry"]
mixed = [1, "two", 3.0, True]
empty = []
print(fruits)
print(mixed)
print(empty)You can also build a list with the list() constructor. It takes any iterable (an object you can loop over) and collects its items into a new list.
letters = list("abc")
numbers = list(range(5))
from_tuple = list((10, 20, 30))
blank = list()
print(letters) # ['a', 'b', 'c']
print(numbers) # [0, 1, 2, 3, 4]
print(from_tuple) # [10, 20, 30]
print(blank) # []Passing a string to list() splits it into single characters, because a string is an iterable of characters. Use ["abc"] if you want a list with one string in it.
You can also repeat a list with *, or join two lists with +.
zeros = [0] * 4
joined = [1, 2] + [3, 4]
print(zeros) # [0, 0, 0, 0]
print(joined) # [1, 2, 3, 4]Repeating with * is safe for immutable items such as numbers. It causes a bug with nested lists, which a later chapter covers.
Basic list properties
Use len() to get the number of items. Use type() to confirm you have a list.
fruits = ["apple", "banana", "cherry"]
print(len(fruits)) # 3
print(type(fruits)) # <class 'list'>
print(len([])) # 0Two checks you will use often:
- An empty list is falsy, so
if not items:tests for emptiness. - Two lists are equal when they have the same items in the same order.
items = []
if not items:
print("no items")
print([1, 2, 3] == [1, 2, 3]) # True
print([1, 2, 3] == [3, 2, 1]) # FalseLists hold references
A list does not contain the objects themselves. It holds references to them. This is why a list can hold items of different types and sizes, and it is the reason aliasing and shallow copies behave the way they do in later chapters.
Common errors
- Writing parentheses instead of square brackets.
(1, 2, 3)is a tuple, not a list. - Expecting
list(5)to work. An integer is not iterable, so Python raisesTypeError. Use[5]orlist(range(5)). - Forgetting that
list("abc")splits a string into characters.
Exercise
What does list("hi") return, and what does list(range(3)) return?
Show answer
list("hi") returns ['h', 'i'] because a string is an iterable of characters. list(range(3)) returns [0, 1, 2].
Exercise
A variable items is set to []. Write a condition that prints "empty" only when the list has no items, and name one reason list(7) fails.
Show answer
Use if not items: print("empty"), or if len(items) == 0:. list(7) fails with TypeError because an integer is not iterable.