Appendix D: Python operators
This appendix lists the Python operators you are likely to need, organised by category.
D.1. Arithmetic operators
| Precedence | Operator | Name | Description |
|---|---|---|---|
Highest |
|
Unary minus |
Negation |
High |
|
Multiplication |
Multiply values |
|
True division |
Floating-point division |
|
|
Floor division |
Integer division (floor) |
|
|
Modulo |
Remainder |
|
Normal |
|
Addition |
Add values |
|
Subtraction |
Subtract value |
D.2. Boolean operators
| Precedence | Operator | Name | Description |
|---|---|---|---|
Highest |
|
Logical NOT |
Inverts truth value |
High |
|
Logical AND |
True if both operands are true |
Normal |
|
Logical OR |
True if either operand is true |
D.3. Comparison operators
| Precedence | Operator | Name | Description |
|---|---|---|---|
Normal |
|
Ordering |
Relational comparisons |
|
Equality |
Value comparison |
|
|
Identity |
Object identity test |
|
|
Membership |
Membership test |
D.4. List operators
Note that + and * both also work on lists. If you "add" two lists, it returns the lists joined together, end to end. So [1, 2] + [3, 4] gives you [1, 2, 3, 4]. If you multiply a list by a number, it repeats it. So [1, 2] * 2 gives [1, 2, 1, 2].
Lists also have another kind of operator: slicing. There are several ways to slice. Imagine we have a list with all the letters of the alphabet: ["a", "b", "c", "d", … "z"] (that triple dots is not Python code, just to save us writing out the full alphabet).
-
letters[2:]would give the list from index 2 onwards. Since index 0 is the first position, index 2 is letter"c"so this will give the letters c to z. -
letters[:2]would give the list up to just before index 2. Since index 2 is letter c, this would just give["a", "b"]. -
letters[2:5]would give the list from index 2 to just before index 5. Therefore this is indexes 2, 3, and 4; letters c to e. -
letters[5:10:2]would give the list from index 5 to just before index 10, in steps of 2. Index 5 is letter f, so this will be["f", "h", "j"]. -
The final variants omit the start or the end:
letters[5::2]returns all letters from 5 onwards in steps of 2. Whereasletters[:5:2]returns all letters up to just before index 5, in steps of 2, so["a", "c", "e"].
D.5. More operators
In this appendix we have omitted some advanced operators. There is a full list of operators in the Python documentation.