Chapter 7 of 15All chapters
Chapter 7 of 15
Lists
The ordered container you will use most.
Making and changing
A list holds an ordered sequence you can change in place. append adds one item, extend adds many, pop removes and returns, and remove deletes by value.
- Lists can hold mixed types, though code is easier to read when they do not.
- sort() reorders in place and returns None. sorted(items) returns a new list.
Comprehensions
A comprehension builds a list from a loop in one expression: [x * 2 for x in range(3)] gives [0, 2, 4]. Adding a condition filters: [x for x in items if x > 0].
- Read it as the output first, then the loop, then the filter.
- Anything longer than one line is clearer as a normal loop.