What you’ll get
Five ping measurements to a server in a single list. Four lines give the worst, the best, the sorted sequence and the average:
# pings.py
pings = [23, 19, 87, 21, 20] # ms
print(max(pings), min(pings))
print(sorted(pings))
print(sum(pings) / len(pings))
python pings.py
# 87 19
# [19, 20, 21, 23, 87]
# 34.0
The average comes out to 34 ms even though four of the five pings sit around 20: one spike at 87 ms pulls the mean up. The median — the middle value of the sorted list — gives a sharper picture:
print(sorted(pings)[len(pings) // 2])
# 21
Square brackets after a list are an index, the element’s position. Counting starts at zero, as in Strings:
len(pings) // 2 gives 2, the third item.
How it works: a row of references
A list’s slots hold references to values, laid out in one contiguous row. That’s why indexing by position is immediate: Python computes the slot’s address from the index without walking from the start.
pings ──► [ [0] | [1] | [2] | [3] | [4] | spare ]
│ │ │ │ │
▼ ▼ ▼ ▼ ▼
23 19 87 21 20
Python keeps spare empty slots at the end of the row. When you call append, the new item takes the next free slot;
once the spare room runs out, Python allocates a larger row and moves the references over. Inserting at the front with
insert(0, x) shifts every remaining element one slot to the right each time. On a 100,000-item list, ten thousand
front insertions run thousands of times slower than appends. When you need a queue that pushes on both ends, use
collections.deque: both ends are fast.
For the same reason, b = a doesn’t copy a list — the second name points to the same row of references, like the label
in Variables and types. Calling b.append(99) changes a too. When you need an independent list, copy it:
b = a.copy() or b = a[:].
Change, sort, slice
You can modify a list in place or build a new one.
| Task | Code | Result |
|---|---|---|
| append to the end | pings.append(22) |
[23, 19, 87, 21, 20, 22] |
| append several items | pings.extend([18, 25]) |
items of the second list added to the end of the first |
| insert at an index | pings.insert(1, 20) |
inserts 20 before index 1 |
| pop the last item | last = pings.pop() |
returns 20 and removes it; pop(0) takes the first |
| remove by value | pings.remove(87) |
removes the first 87; missing value raises ValueError |
| check membership | 87 in pings |
True |
| length, bounds, sum | len, min, max, sum |
work on any list of numbers |
Sorting comes in two forms:
sorted(pings)returns a new sorted list and leaves the original untouched. Passreverse=Truefor descending order:sorted(pings, reverse=True)returns[87, 23, 21, 20, 19].pings.sort()rearranges elements insidepingsitself and returnsNone. That’s where the common bugpings = pings.sort()comes from — the name ends up pointing toNone.
Slicing works the same way as on strings in Strings and always returns a new list:
pings[:3] # [23, 19, 87] — first three
pings[-2:] # [21, 20] — last two
sorted(pings)[:3] # [19, 20, 21] — three best
Split a string into a list with split, and glue a list of strings back together with join:
"23,19,87,21,20".split(",") # ['23', '19', '87', '21', '20']
", ".join(["web1", "web2", "db1"]) # 'web1, web2, db1'
split() with no arguments splits on any whitespace and line breaks. join expects strings: if the list holds numbers,
convert them with str first.
Tuples: a row that doesn’t change
Write a tuple (tuple) in parentheses. Once created, its elements can’t be replaced or appended to:
size = (1920, 1080)
size[0] = 1280
# TypeError: 'tuple' object does not support item assignment
Use a tuple when values belong together as a single record: a screen resolution, a (host, port) pair, or a
(size, path) pair as in What takes up space. Immutability guards against accidental edits: a function that receives
a tuple can’t mutate it. A single-element tuple needs a trailing comma — (22,) — otherwise (22) stays a plain number
in parentheses.
Tuple elements (and list elements too) unpack into separate names on one line:
width, height = size # width = 1920, height = 1080
enumerate from Loops works the same way: each step yields an (index, value) pair, and the loop unpacks it
into two names — for n, p in enumerate(pings, start=1):. If the count of names on the left doesn’t match the items on
the right, Python stops with a ValueError.
Take it further
A for loop over the list, a condition and a counter — all from previous chapters.
pings = [23, 19, 87, 21, 20]
slow = 0
for p in pings:
if p > 50:
slow += 1
print(slow)
# 1median function for any list — including even lengthsSort with sorted so the original list stays intact. For an even length there are two middle elements: take their average.
def median(values):
s = sorted(values)
mid = len(s) // 2
if len(s) % 2:
return s[mid]
return (s[mid - 1] + s[mid]) / 2
print(median([23, 19, 87, 21, 20])) # 21
print(median([23, 19, 87, 21])) # 22.0"23, 19, 87, 21, 20" into a list of integers and find the lowest pingSplit on commas with split, then strip spaces with strip() and convert each part with int inside a loop.
raw = "23, 19, 87, 21, 20"
nums = []
for part in raw.split(","):
nums.append(int(part.strip()))
print(nums, min(nums))
# [23, 19, 87, 21, 20] 19If it doesn’t work
IndexError: list index out of range
- Cause
- A position past the end of the list: in a five-element list, the last index is
[4]. - Fix
- Get the last item with
[-1], and check the length withlen(). A slice past the end raises no error.
TypeError: 'NoneType' object is not subscriptable
- Cause
- You wrote
pings = pings.sort():sort()sorts in place and returnsNone. - Fix
- Call
pings.sort()without assignment, or build a new list withsorted(pings).
TypeError: 'tuple' object does not support item assignment
- Cause
- Changing a tuple element in place:
size[0] = 1280. A tuple can’t be modified after creation. - Fix
- If the values need to change, use a list
[1920, 1080]or create a new tuple.
ValueError: too many values to unpack (expected 2, got 3)
- Cause
- Unpacking has more values on the right than names on the left:
host, port = ("web1", 22, "ssh"). - Fix
- Match the number of names to the items, or collect the rest with a star:
host, port, *rest = ….
Changed a copy of a list, and the original changed too
- Cause
b = adoesn’t copy the list; it attaches a second name to the same object in memory.- Fix
- Make an explicit copy:
b = a.copy()orb = a[:].