A list stores values in the order you wrote them, inside square brackets and separated by commas. Any type can go in, several types can share one list, and the same value may appear more than once.
scores the number 4 sits at two positions and counts twice.An index picks one value out of the list. A slice picks a section and hands back a new list, leaving the original where it was.
| Form | Meaning | Example | Result |
|---|---|---|---|
| items[i] | the value at position i | items[0] | 'ant' |
| items[-i] | counting back from the end | items[-1] | 'fox' |
| items[a:b] | from a up to, and not including, b | items[1:4] | ['bee', 'cat', 'dog'] |
| items[:b] | from the start up to b | items[:2] | ['ant', 'bee'] |
| items[a:] | from a to the end | items[4:] | ['elk', 'fox'] |
| items[a:b:c] | same section, jumping by c | items[0:6:2] | ['ant', 'cat', 'elk'] |
| items[::-1] | a reversed copy | items[::-1] | ['fox', 'elk', ...] |
An index that does not exist raises IndexError and stops the program. A slice that runs past the end raises no error: it returns whatever positions it did find, and an empty list when it found none.
A list is mutable: the object keeps its name and its identity while its content changes. Assignment by index replaces one value, and the methods below add or drop values.
Each row below starts from the same list on the left, and the panel on the right shows what it looks like right after the call.
items[1] = "owl"replaces the value at position 1.append("owl")adds a value at the end.insert(1, "owl")puts a value at position 1 and pushes the rest right.remove("bee")drops the first matching value, raises ValueError when absentlast = .pop()drops the last value and returns it last = 'cat'.sort()reorders the list in place, returns None.reverse()flips the order in place, returns Nonea + bbuilds a new list holding both, in order"cat" in itemstrue when the value is somewhere in the list, false otherwise| Call | What it returns | Write it as |
|---|---|---|
| .append, .insert, .remove, .sort, .reverse | None | items.sort() |
| .pop | the value it removed | value = items.pop() |
| a + b, v in items | a new value, items stays as it was | result = a + b |
A tuple is written with parentheses and is fixed the moment it is created. Reading works as it does in a list, and every attempt to write raises an error.
len and in behave as in a list. Slicing a tuple returns a tuple.point[0] = 9 raises TypeError.Because the size of a tuple is fixed, Python can hand its values to several names in one line. That move is called unpacking, and the number of names has to match the number of values.
Reach for a tuple when the shape of the data never changes: a coordinate, a colour, a pair of values returned together. The fixed size is a promise to whoever reads the code later, and it also protects the values from being edited by accident.
The two fragments differ in one character: square brackets on the left, parentheses on the right. Run both and read what Python says about the second one.
The error arrives at line 2, so the print on line 3 never runs. An immutable object refuses the assignment rather than making a quiet copy.
| Question | list | tuple |
|---|---|---|
| Written with | [ ] | ( ) |
| Order kept | Yes | Yes |
| Repeats kept | Yes | Yes |
| Changes after creation | Yes, in place | Never |
| Index and slice | Yes | Yes |
| Typical use | A collection that grows, shrinks and gets sorted | A record with a fixed shape, or values returned together |
A set holds each value once and holds no positions. Writing the same value twice changes nothing, and asking for element 0 raises TypeError because there is no element 0 to ask for.
v in tags is answered without walking through the values, so it stays fast on large collections.Empty braces build a dictionary rather than a set, so an empty set has to be written set(). And the order you see when printing a set is not the order you wrote and may change between runs, so never write code that depends on it.
A set changes in place just like a list, and a pair of sets can combine into a third one. Each row below starts from the same set on the left, and the panel on the right shows the result right after the call.
.add("green")puts a value in, or leaves the set as it was when already present.discard("red")drops a value when present, stays quiet when absent.remove("red")drops a value, raises KeyError when absent"blue" in tagstrue when the value is a member, false otherwiseA | Bunion, every value in either set, also written A.union(B)A & Bintersection, only the values present in both, also written A.intersection(B)A - Bdifference, in A and not in B, also written A.difference(B)A ^ Bsymmetric difference, in one set or the other, not in both, also written A.symmetric_difference(B)A <= Btrue when every value of A is also in B, also written A.issubset(B)| Call | What it returns | Write it as |
|---|---|---|
| .add, .discard, .remove | None | tags.add("green") |
| |, &, -, ^, <= | a new set, or a boolean for <= | result = A | B |
| Question | list | tuple | set |
|---|---|---|---|
| Written with | [1, 2, 2] | (1, 2, 2) | {1, 2} |
| Position matters | Yes | Yes | No |
| Changes after creation | Yes | No | Yes |
| Repeats kept | Yes | Yes | No |
| Index and slice | Yes | Yes | No |
| Reach for it when | The order is part of the meaning and the content moves | The record has a fixed shape that must stay fixed | You care about membership, not about position |
Each type has a function that builds it from any of the others. The conversion keeps whatever the target type promises and drops the rest.
Passing a list through a set is the shortest way to drop duplicates, and it costs you the original order. When the order matters, wrap the result in sorted, which returns a list arranged from small to large.
The for loop from the previous guide walks all three types with the same header, one value per pass. Counting with range is only needed when the position itself is part of the work.
Trace each fragment before pressing Check. The answer button is there for when your trace and the verdict disagree.
append, insert, remove, pop, sort and reverse, and predict the list each one leaves behind.