List indexing and slicing in Python: reach in by position
The latest day's sales. The three best-selling sizes. The order in the exact middle. Each is a question about position, and Python's bracket syntax answers all three.
The big idea
An index in square brackets selects one item by position, counting from 0; a slice [start:stop] selects a range, excluding stop.
See it in code
Positive indexes count from the front, starting at 0. Negative indexes count from the back, starting at -1:
daily_tees = [42, 57, 38, 64, 71, 95, 88]
print("First day:", daily_tees[0])
print("Last day:", daily_tees[-1])
print("Day before that:", daily_tees[-2])First day: 42 Last day: 88 Day before that: 95
[-1] is always the last item, however long the list is. That's far safer than [6], which breaks the moment an eighth day is added.
A slice takes a section. [:3] means "from the start, up to but not including position 3," so it returns three items:
size_sales = [18, 64, 120, 97, 41]
ranked = sorted(size_sales, reverse=True)
print("Ranked:", ranked)
print("Top three:", ranked[:3])
print("The rest:", ranked[3:])Ranked: [120, 97, 64, 41, 18] Top three: [120, 97, 64] The rest: [41, 18]
ranked[:3] and ranked[3:] split the list cleanly with no overlap, because the stop index is excluded from the first and the start index is included in the second.
Compute an index and you can find the middle. Sort the order values, then take the item at len // 2: the median, which one huge order can't distort:
order_values = [38, 38, 52, 76, 38, 114, 45, 38, 600]
order_values.sort()
mean = sum(order_values) / len(order_values)
median = order_values[len(order_values) // 2]
print(f"Mean order: ${mean:.2f}")
print(f"Median order: ${median}")Mean order: $115.44 Median order: $45
One $600 bulk order drags the mean above $115, while the median stays at $45. For "what does a typical customer spend?", the median is the honest answer.
Slices work on any sequence, strings included. sku[:3] takes a product code's prefix, and dna[i:i + 3] cuts a codon out of a strand.
Try it yourself
Print ranked[1:4] and ranked[-2:] after predicting each. Then remove the .sort() line from the median program and see how wrong "the middle" becomes on unsorted data.
The common mistake
Reading a slice's stop as inclusive. ranked[0:2] returns two items, positions 0 and 1, not three. The number of items in [a:b] is b - a.
What it unlocks
Indexing assumes you know where things are; list methods cover sorting and changing a list, and enumerate gives you the position and the item together in a loop.