Skip to content

Instantly share code, notes, and snippets.

@timsgardner
Created September 26, 2023 23:16
Show Gist options
  • Save timsgardner/220a9ed9dfb86712e1e073a1251921cc to your computer and use it in GitHub Desktop.
Save timsgardner/220a9ed9dfb86712e1e073a1251921cc to your computer and use it in GitHub Desktop.
Python Operator Precedence Cheat Sheet

Python Operator Precedence Cheat Sheet

What is Operator Precedence?

Operator precedence defines the order in which operations are performed when evaluating an expression. In Python, certain operators are evaluated before others. For example, in the expression 1 + 2 * 3, multiplication (*) has higher precedence than addition (+), so 2 * 3 is evaluated first, followed by 1 + 6, resulting in 7.

Understanding operator precedence is essential for accurately interpreting and writing Python code. It dictates how complex expressions are evaluated and helps prevent logical errors.

Precedence Order (Highest to Lowest)

  1. Parentheses

    • (expression)
  2. Exponentiation

    • **
  3. Unary Plus, Unary Minus, Bitwise NOT

    • +x, -x, ~x
  4. Multiplication, Division, Modulus

    • *, /, //, %
  5. Addition, Subtraction

    • +, -
  6. Bitwise Shift

    • <<, >>
  7. Bitwise AND

    • &
  8. Bitwise XOR

    • ^
  9. Bitwise OR

    • |
  10. Comparison Operators

    • <, <=, >, >=, ==, !=
  11. Identity Operators

    • is, is not
  12. Membership Operators

    • in, not in
  13. Logical NOT

    • not
  14. Logical AND

    • and
  15. Logical OR

    • or
  16. Conditional Operator

    • expression1 if condition else expression2
  17. Assignment Operators

    • =, +=, -=, *=, /=, %=, **=, //=, &=, |=, ^=, <<=, >>=

Examples

Using not with Comparison Operators

result = not 5 > 3  # Equivalent to not (5 > 3)

Using not with Arithmetic Operators

result = not 5 + 3  # Equivalent to not (5 + 3)

Using not with and and or

result = not True or False  # Equivalent to (not True) or False
result = not True and False  # Equivalent to (not True) and False

Multiple not Operators

result = not not True  # Equivalent to not (not True)

Using Parentheses for Clarity

To make the precedence explicit, use parentheses:

result = (not True) and (5 > 3)

This cheat sheet aims to provide a quick reference for understanding Python's operator precedence. When in doubt, use parentheses to clarify the order of operations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment