Operators

Arithmetic operators:

  • addition
  • subtraction
  • multiplication
  • division
  • floor division
  • modulus
  • exponentiation

In [ ]:
3 + +5, 3 + 5., -3 + True, 0X2a + -0xB, -0O70 + 0o30, -0B101 + 0b110, -2j + 5J

In [ ]:
+3 - -5, 3. - 5, 2.5j - -1j

In [ ]:
3e-4 * 5.0E0, -3 * False, -2.5j * 5J

In [ ]:
13 / 5, -13. / 5, 13. / -5., -13. / -5., 13j / 5J

x // and x % y are such that:

  • x = (x // y) * y + x % y;
  • -|y| < x % y < |y|;
  • the sign of x % y is equal to the sign of y.

In [ ]:
13 // 5, -13. // 5, 13. // -5., -13 // -5., 3.5 // 2

In [ ]:
13 % 5, -13. % 5, 13. % -5., -13 % -5., 3.5 % 2

$i^i = e^{-\pi/2}$


In [ ]:
2 ** 3, -2. ** -1, 4 ** -0.5, (-1) ** 0.5, -3.8 ** 0, 1j ** 1j

Bitwise operators:

  • ones complement
  • AND
  • OR (inclusive or)
  • XOR (exclusive or)
  • right shift
  • left shift

...

-4 : ...1...100

-3 : ...1...101

-2 : ...1...110

-1 : ...1...111

 0 : ...0...000

 1 : ...0...001

 2 : ...0...010

 3 : ...0...011

 4 : ...0...100

...


In [ ]:
~34, ~3, ~2, ~1, ~0, ~-1, ~-2, ~-3, ~-34

In [ ]:
9 & 10, -9 & 10, 9 & -10, -9 & -10

In [ ]:
9 | 10, -9 | 10, 9 | -10, -9 | -10

In [ ]:
9 ^ 10, -9 ^ 10, 9 ^ -10, -9 ^ -10

In [ ]:
5 >> 2, -5 >> 2

In [ ]:
5 << 2, -5 << 2

Relational operators:


In [ ]:
1 == 1., 0 != False

In [ ]:
1 <= 1 < 2 >= 2 > 1

Boolean operators


In [ ]:
not 3.3, not []

In [ ]:
True and (1, 2, 3), () and 1 / 0

In [ ]:
{} or {0}, {'A': 1, 'B': 2} or 1 / 0

Identity operators


In [ ]:
2 is 2, [] is [], 2 is not 2., True is not 1

Membership operators


In [ ]:
'B' in {'A': 1, 'B': 2, 'C': 3}, 0 not in [[0]]

Assignment operators


In [ ]:
x = 1
x <<= 2
print(x)
x >>= 1
print(x)
x += 1
print(x)
x -= 2
print(x)
x *= 3
print(x)
x /= 2
print(x)
x %= 2
print(x)
x //= -2
print(x)

Precedence and associativity

From highest to lowest precedence:

  • **
  • ~   unary +   unary -
  • *   /   //   %
  • binary +   binary -
  • >>   <<
  • &
  • ^
  • |
  • <=   <   >   >=   ==   !=   is   is not   in   not in
  • =   (and all augmented assignments)
  • not
  • and
  • or

In [ ]:
20 / 10 / 2, 20 // (10 // 2)

In [ ]:
7 % 5 % 3, 7 % (5 % 3)

In [ ]:
2 ** 3 ** 2, (2 ** 3) ** 2

In [ ]:
1 << 2 << 1, 1 << (2 << 1)

In [ ]:
8 >> 2 >> 1, 8 >> (2 >> 1)