Lists, tuples, slicing & sorting
Store, slice, sort and unpack sequences confidently.
By Invicly Tech, , in Python Programming from Zero. About 12 minutes to read.
In short
Lists hold an ordered, changeable sequence of items; tuples hold an ordered, fixed record. Both support indexing, slicing and unpacking, and sorted() can order any sequence by a key you choose.
Explained simply
A list holds many values in a fixed order, written inside square brackets: [3, 1, 2]. Lists can grow, shrink and change after you create them, which is what mutable means. They can hold any type, even a mix, but most lists hold one kind of thing, such as names or prices.
Positions start at 0, and negative positions count from the end, so items[-1] is the last item. Slicing, items[1:3], cuts out a piece as a new list. These are the same rules you already know from strings.
Sorting comes in two forms. sorted(items) gives you a new sorted list and leaves the original alone. items.sort() sorts the list itself and returns None. Both accept a key function that says what to compare: the length, one field of a record, or a lower-case version of a word.
A tuple is like a list that cannot change. Use it for a small record where each position has a meaning, like (name, age) or (x, y). You can unpack a tuple into separate names in one step: name, age = person. Functions often return tuples for exactly this reason.
Press Play on a diagram to walk through it one step at a time.
- Ordered, allows duplicates
- Mutable: append, remove, sort
- For collections that grow
- Index and slice
- Ordered, allows duplicates
- Immutable once created
- For fixed records like (x, y)
- Can be a dict key
- Unordered, no duplicates
- Mutable: add, discard
- Fast membership tests
- No indexing
- Add
- append(x): one item at the end
- extend(other): every item of other
- insert(i, x): at position i
- Remove
- remove(x): first match by value
- pop(i): by index, returns it
- clear(): everything
- Find
- index(x): position or ValueError
- count(x): how many
- x in items: True or False
- Reorder
- sort(): in place, returns None
- reverse(): in place
- Copy
- copy() or items[:]
- Shallow: nested items are shared
- Adds one item: the list itself
- a becomes [1, 2, [4, 5]]
- Changes a in place
- Adds each item separately
- a becomes [1, 2, 4, 5]
- Changes a in place
- Builds a brand-new list
- a itself is unchanged
- Assign it to keep the result
In depth
How a list is stored, and what each operation costs
In CPython, the standard Python, a list is a dynamic array: one block of memory holding references (pointers) to the item objects, side by side. That layout explains its speed.
Reading or writing items[i] jumps straight to position i, so it takes the same time for any size. append() is also fast: the list reserves a little spare room, and only occasionally has to move to a bigger block. Working at the front is slow, though. insert(0, x) and pop(0) must shift every other item one place, so they get slower as the list grows. x in items and items.remove(x) scan from the start until they find a match.
For a queue where you add at one end and remove at the other, use collections.deque, whose appendleft() and popleft() are fast. For frequent membership tests on big data, use a set.
- items[i] and items[i] = x
- append(x)
- pop() from the end
- len(items)
- insert(0, x)
- pop(0)
- remove(x)
- x in items
Slicing in full
A slice has three parts, items[start:stop:step], and every part is optional. A missing start means the beginning, a missing stop means the end, and the step defaults to 1. A negative step walks backwards, so items[::-1] is a reversed copy. Slices never raise IndexError: items[5:100] on a short list just returns what exists, often an empty list.
A slice always builds a new list (a shallow copy), so changing the slice does not change the original.
Slices also work on the left side of =. items[1:3] = ["a", "b", "c"] replaces two items with three, so the list can grow or shrink. del items[::2] deletes every second item. items[:] = [] empties the list in place, which matters when other names point at the same list: they all see it emptied, while items = [] would only move one name to a new list.
- items[:3] is the first three, items[-3:] the last three
- items[::2] is every second item
- items[:] is a quick shallow copy
Sorting with key functions
sorted() accepts any iterable (a list, tuple, set, dict keys, even a string) and always returns a list. It uses an algorithm called Timsort, which takes O(n log n) time and is stable: items that compare equal keep their original order.
The key function is called once per item, and the items are ordered by those results. key=len sorts words by length, key=str.lower ignores case, and key=lambda p: p[1] sorts records by their second field. Return a tuple to sort by several things: key=lambda p: (p[1], -p[2]) sorts by field 1, then by field 2 in descending order (the minus sign flips numbers). reverse=True reverses the whole order.
min() and max() take the same key argument, so max(staff, key=lambda s: s[2]) finds the best-paid person without sorting. Sorting a list that mixes types that cannot be ordered, such as ints and strings, raises TypeError.
- Step 1Call key on each item
len("kiwi") is 4, len("fig") is 3
- Step 2Compare the keys
The words themselves are not compared
- Step 3Keep ties in order
Stable: equal keys stay as they were
- Step 4Build a new list
The original list is unchanged
Tuples, packing and unpacking
It is the comma that makes a tuple, not the parentheses: t = 1, 2 is a tuple, and a one-item tuple needs a trailing comma, (5,). Building a tuple like this is called packing; pulling it apart is unpacking.
Unpacking needs the counts to match, or you get ValueError. A starred name collects the rest into a list: first, *middle, last = [1, 2, 3, 4, 5] gives 1, [2, 3, 4] and 5. Unpacking also works in for loops (for name, age in people) and for nested data, and it is how a, b = b, a swaps two values.
A tuple cannot change, but the objects inside it can. A tuple holding a list can still see that list change, and such a tuple is not hashable. A tuple of numbers or strings is hashable, so it can be a dict key: {(0, 0): "origin"}.
Choose by meaning: a list for a collection of similar things that changes, a tuple for one fixed record. For records with many fields, a named tuple or a dataclass makes the fields readable by name.
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Create, index and slice lists~50m
- 2Append, insert and remove items~50m
- 3Sort with sorted() and key functions~50m
- 4Pack and unpack tuples~50m
- 5Choose tuples for fixed records~50m
Key points
- items[1:3] slices; items[-1] is the last item.
- append() adds one item, insert(i, x) adds at a position, remove(x) deletes by value.
- sorted(items) returns a new list; items.sort() sorts in place and returns None.
- Pass key= to sort by something else, e.g. sorted(words, key=len).
- Unpack tuples directly: name, age = ("Ana", 31).
Key terms
Tap a card to flip it. 0/5 known
Examples
nums = [5, 2, 9, 1]
nums.append(7)
nums.insert(0, 10)
nums.remove(9)
print(nums, nums[1:3], nums[-1]) # [10, 5, 2, 1, 7] [5, 2] 7
print(sorted(nums)) # [1, 2, 5, 7, 10]
print(sorted(nums, reverse=True))
people = [("Ana", 31), ("Bo", 25), ("Cy", 40)]
by_age = sorted(people, key=lambda p: p[1])
print(by_age[0]) # ('Bo', 25)
name, age = people[0]
print(name, age) # Ana 31Sorting staff by department, then salary
Each record is a tuple (name, department, salary). Step 1: the key returns a tuple, so Python sorts by department first and, for equal departments, by the second element. Step 2: -s[2] turns a high salary into a low number, giving descending pay inside each department. Step 3: Bo and Di have the same department and pay, so the stable sort keeps them in their original order. Step 4: max() with the same style of key finds the top earner without sorting at all.
staff = [("Ana", "dev", 5200), ("Bo", "ops", 4100),
("Cy", "dev", 6100), ("Di", "ops", 4100)]
by_dept = sorted(staff, key=lambda s: (s[1], -s[2]))
for name, dept, pay in by_dept:
print(f"{dept:<5}{name:<4}{pay}")
# dev Cy 6100
# dev Ana 5200
# ops Bo 4100
# ops Di 4100
top = max(staff, key=lambda s: s[2])
print(top[0]) # CyA leaderboard with slicing and star unpacking
You have raw scores and want the podium. Step 1: sorted(..., reverse=True) puts the highest first without touching the original list. Step 2: [:3] takes the top three; if there were fewer scores, the slice would simply be shorter. Step 3: star unpacking separates the winner from the rest. Step 4: [-1] gives the lowest score and [::2] every second one, all without loops or index arithmetic.
scores = [72, 95, 88, 61, 99, 80]
ranked = sorted(scores, reverse=True) # [99, 95, 88, 80, 72, 61]
top3 = ranked[:3]
first, *others = top3
print(first, others) # 99 [95, 88]
print(ranked[-1]) # 61, the lowest
print(ranked[::2]) # [99, 88, 72]
print(scores) # unchanged: [72, 95, 88, 61, 99, 80]Quick reference
- items[-1] is the last item, items[-2:] the last two, items[::-1] a reversed copy
- append(x) adds one item; extend(other) adds every item of other
- items.pop() removes and returns the last item; pop(0) is slow on big lists, use deque
- sorted(people, key=lambda p: (p[1], -p[2])) sorts by two fields, the second descending
- Python's sort is stable: items with equal keys keep their original order
- first, *rest = items splits off the first item and puts the rest in a list
- t = 5, is a one-item tuple: the comma makes the tuple, not the parentheses
- items[:] = [] empties a list in place, so every other name sees the change
Common mistakes
- Writing nums = nums.sort(), which sets nums to None.
- Forgetting the comma in a one-item tuple: (5,) not (5).
- Using a list where a set would make membership checks much faster.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Given nums = [4, 8, 15, 16, 23, 42], use only slicing to print the first three items, the last two, every second item and the whole list reversed.
- Exercise 2medium
Sort people = [("Cy", 30), ("Ana", 25), ("Bo", 30), ("Di", 25)] by age from oldest to youngest, and alphabetically by name for equal ages. Then get the first person's name with unpacking.
- Exercise 3hard
Write rotate(items, k) that returns a new list rotated right by k places, so rotate([1, 2, 3, 4, 5], 2) is [4, 5, 1, 2, 3]. It must work when k is larger than the length and for an empty list, and use no loops.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between a Python list and an array?
- A list is a dynamic array of references that can hold any objects. The array module and NumPy arrays store one numeric type compactly, which is much better for large amounts of numbers.
- How do I remove duplicates from a list but keep the order?
- Use list(dict.fromkeys(items)). Dicts keep insertion order, so the first copy of each item stays in place; set(items) also removes duplicates but loses the order.
- Why does sort fail with TypeError: '<' not supported?
- The list mixes values that cannot be compared, such as numbers and strings or None. Clean the data first, or pass a key that returns comparable values.
- Is a tuple faster than a list?
- Tuples are slightly smaller and quicker to create, but the difference rarely matters. Choose by meaning: a tuple for a fixed record, a list for a collection that changes.