Pick an item by position
list[n] is the item at position n, list[-1] is the last item, and list[a:b] is a new list of the items in between. The positions work just as they do for text.
- Read the first, last and nth item, and take a slice of a list
- Loop over positions with
range(len(items))when you need an item's neighbour - Recognise
IndexErrorand the off-by-one mistakes that cause it
A list's items have positions, just as a text's characters do. ratings[0] is the first item, ratings[-1] is the last, and ratings[1:3] is a new list holding the items at positions 1 and 2. All the rules from the Strings & Text module carry over. Positions start at 0, the end of a slice is not included, and a slice past the end is shorter instead of an error.
Run each example to see what it prints. Running examples doesn't count toward progress.
ratings = [4.5, 3, 5, 2.5, 4] print(ratings[0], ratings[-1], len(ratings)) print(ratings[1:3]) print(ratings[-2:])
ratings = [4.5, 3, 5, 2.5, 4] print(ratings[len(ratings) - 1]) print(ratings[5])
Some questions compare an item with its neighbour: *how much did the temperature change since yesterday?* for t in highs gives you each item but not the one before it. Loop over the positions instead, with range(len(highs)), and read highs[i] and highs[i - 1]. Start at 1, because position 0 has no day before it.
highs = [6.7, 7.2, 3.3, 7.2, 3.9, -2.1] for i in range(1, len(highs)): change = highs[i] - highs[i - 1] print(f"Day {i + 1}: {change:+.1f}")
When to use it: use positions for the first or last item, a fixed window such as the last 3 days, or a comparison with a neighbour. When you only need each item, for item in items is simpler. Mistakes to avoid:
- Starting a neighbour loop at 0. Then
highs[0 - 1]quietly reads the *last* item. - Using
len(items)as a position.
items[n],items[-1]anditems[a:b]work on lists as they do on text. A slice of a list is a new list.- Loop over
range(1, len(items))when each item is compared with the one before it. - Five items sit at positions 0 to 4. Asking for position 5 raises IndexError.
- Next: change a list in place by adding, replacing and removing items.