Skip to content
Tactiverge

Python reference

Lists and indexing

Also called: list · array · index · append · len · negative index

Definition

A list is an ordered, changeable collection written in square brackets. Items are numbered from 0, and negative indices count back from the end.

Picture it

readings[0] is the first sample, readings[-1] the latest. A list of length n has valid indices 0 to n − 1, so readings[n] is always an IndexError. append adds to the end in constant time, which makes lists handy for logging sensor data.

Worked example

readings = [12, 15, 11, 18]. What are readings[1], readings[-1], len(readings) and sum(readings) / len(readings)?

  1. Index 1 is the second item: 15
  2. -1 is the last: 18
  3. There are 4 items
  4. Sum 56 / 4 = 14.0

Answer15, 18, 4 and 14.0.

✓ The 3 numbers in this answer are recomputed from scratch by an automated test.

In Python

readings = []
for _ in range(3):
    readings.append(read_sensor())
print(readings[-1])  # most recent

Common misconceptions

  • Misconception: The first item is index 0, not 1.
  • Misconception: b = a does not copy a list; use a.copy() or list(a).