Operators and Expressions

Read this to learn more about operators and expressions.

If you had an expression such as 2 + 3 * 4, is the addition done first or the multiplication? Our high school maths tells us that the multiplication should be done first. This means that the multiplication operator has higher precedence than the addition operator.

The following table gives the precedence table for Python, from the lowest precedence (least binding) to the highest precedence (most binding). This means that in a given expression, Python will first evaluate the operators and expressions lower in the table before the ones listed higher in the table.

The following table, taken from the Python reference manual, is provided for the sake of completeness. It is far better to use parentheses to group operators and operands appropriately in order to explicitly specify the precedence. This makes the program more readable. See Changing the Order of Evaluation below for details.

  • lambda : Lambda Expression
  • if - else : Conditional expression
  • or : Boolean OR
  • and : Boolean AND
  • not x : Boolean NOT
  • in, not in, is, is not, <, <=, >, >=, !=, == : Comparisons, including membership tests and identity tests
  • | : Bitwise OR
  • ^ : Bitwise XOR
  • & : Bitwise AND
  • <<, >> : Shifts
  • +, - : Addition and subtraction
  • *, /, //, % : Multiplication, Division, Floor Division and Remainder
  • +x, -x, ~x : Positive, Negative, bitwise NOT
  • ** : Exponentiation
  • x[index], x[index:index], x(arguments...), x.attribute : Subscription, slicing, call, attribute reference
  • (expressions...), [expressions...], {key: value...}, {expressions...} : Binding or tuple display, list display, dictionary display, set display

The operators which we have not already come across will be explained in later chapters.

Operators with the same precedence are listed in the same row in the above table. For example, + and - have the same precedence.