Python 3: Operators

By Xah Lee. Date: . Last updated: .

Arithmetic Operators

Arithmetic
purposesyntaxfunction
additiona + badd(a, b)
Subtractiona - bsub(a, b)
Negation- aneg(a)
Multiplicationa * bmul(a, b)
Divisiona / btruediv(a, b)
Divisiona // bfloordiv(a, b)
Moduloa % bmod(a, b)
Exponentiationa ** bpow(a, b)

The “function” column is the function from the “operator” module. You can use it after you import operator. example:

# -*- coding: utf-8 -*-
# Python 3

import operator

print(operator.add(3,4))  # prints 7

10.3. operator — Standard operators as functions — Python v3.3.3 documentation #mapping-operators-to-functions

Assignment Operators

# -*- coding: utf-8 -*-
# Python 3

# add and assign
c = 0
c += 1
print(c)                        # 1

# substract and assign
c = 0
c -= 2
print(c)                        # -2

# multiply and assign
c = 2
c *= 3
print(c)                        # 6

# exponent and assign
c = 3
c **= 2
print(c)                        # 9

# divide and assign
c = 7
c /= 2
print(c)                        # 3.5

# modulus (remainder) and assign
c = 13
c %= 5
print(c)                        # 3

# quotient and assign
c = 13
c //= 5
print(c)                        # 2

Note: Python doesn't support ++ or --.

Warning: ++i may not generate any error, but it doesn't do anything.

Bit Operators

Bit Operators
purposesyntaxfunction
anda & band_(a, b)
ora | bor_(a, b)
xora ^ bxor(a, b)
invert~ ainvert(a)
Right Shifta >> brshift(a, b)
Left Shifta << blshift(a, b)
# -*- coding: utf-8 -*-
# Python 3

# 0b101 would mean binary 101
# the "{:2b}" means print in binary, and use 2 slots.

# bitwise And
print( "{:2b}".format(0b11 & 0b10) )   # binary 10


# bitwise Or
print( "{:2b}".format(0b11 | 0b10) )   # binary 11

# xor. true if both sides differ
print( "{:2b}".format(0b00 ^ 0b10) )   # binary 10

# binary invert
print( "{:2b}".format(~ 0b1) )   # binary -10  (odd result!)

Sequence Operators

Sequence Operators
purposesyntaxfunction
get itemobj[k]getitem(obj, k)
assign itemobj[k] = vsetitem(obj, k, v)
delete itemdel obj[k]delitem(obj, k)
joinseq1 + seq2concat(seq1, seq2)
if existobj in seqcontains(seq, obj)
format strings % objmod(s, obj)

Boolean Operators

Boolean Operators
purposesyntaxfunction
to booleanobjtruth(obj)
notnot anot_(a)
equala == beq(a, b)
not equala != bne(a, b)
less thana < blt(a, b)
less equala <= ble(a, b)
greatera > bgt(a, b)
greater equala >= bge(a, b)
same objecta is bis_(a, b)
not same objecta is not bis_not(a, b)

2. Lexical analysis — Python v3.3.3 documentation #operators

Ask me question on patreon