ZetCode

Python operator

last modified November 17, 2026 Python 3.15

In this article we cover Python operators.

An operator is a special symbol or keyword which indicates that a certain computation is carried out. Operators in programming languages are taken from mathematics. Programs work with data, and operators are used to process it. An operand is one of the inputs of an operator.

Python has these kinds of operators:

Unary and binary operators

Operators that work with one operand are called unary operators. Those that work with two operands are called binary operators. The + and - signs can be addition and subtraction operators as well as unary sign operators, depending on the situation. The plus sign can indicate a positive number, but it is mostly not used. The minus sign changes the sign of a value. Multiplication and addition are binary operators.

>>> +2
2
>>> a = 1
>>> -a
-1
>>> -(-a)
1
>>> 3 * 3
9
>>> 3 + 3
6

Assignment

The assignment = binds a value to a variable. In mathematics, the = sign has a different meaning; in an equation, it says that the left side equals the right side. In Python, x = x + 1 is legal: the right side is evaluated first and the result is bound to x. A value can be assigned to several variables at once, and tuple unpacking assigns several values in one statement; it is the idiomatic way to swap two variables. We cannot assign to a literal.

>>> x = 1
>>> x
1
>>> x = x + 1
>>> x
2
>>> a = b = c = 4
>>> print(a, b, c)
4 4 4
>>> a, b = 1, 2
>>> a, b = b, a
>>> print(a, b)
2 1
>>> 3 = y
  File "<stdin>", line 1
    3 = y
    ^
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?

Arithmetic operators

The following is a table of arithmetic operators in Python.

SymbolName
+Addition
-Subtraction
*Multiplication
/Division
//Floor division
%Modulo
**Power
@Matrix multiplication

The @ operator is not implemented by any built-in type; it is used by libraries such as NumPy and by our own classes. The following example shows the common arithmetic operations.

arithmetic.py
a = 10
b = 11
c = 12

add = a + b + c
sub = c - a
mult = a * b
div = c / 3
power = a ** 2

print(add, sub, mult, div)
print(power)
print(2 ** 100)

All these are known operators from mathematics. Python integers have arbitrary precision, so 2 ** 100 is computed exactly.

$ python arithmetic.py
33 2 110 4.0
100
1267650600228229401496703205376

Division operators

There are three operators dealing with division: true division /, floor division //, and modulo %.

division.py
print(9 / 3)
print(9 / 4)
print(9 // 4)
print(9 % 4)

print(-9 // 4)
print(-9 % 4)
print(divmod(-9, 4))

print(9.5 // 2)
print(9.5 % 2)

The / operator always returns a float, even when the result is a whole number. The // operator rounds the result down, towards negative infinity, so -9 // 4 is -3, not -2. The % operator returns the remainder of that division; its result has the sign of the divisor, which makes x == (x // y) * y + x % y always hold. The built-in divmod function returns both values. Both operators work with floats as well.

$ python division.py
3.0
2.25
2
1
-3
3
(-3, 3)
4.0
1.5

Operators on sequences

The + operator concatenates strings, lists, and tuples, and the * operator repeats them. We cannot add integers and strings; the number must be converted to a string first with the str function.

>>> 'return' + 'of' + 'the' + 'king'
'returnoftheking'
>>> 3 + ' apples'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    3 + ' apples'
    ~~^~~~~~~~~~~
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> str(3) + ' apples'
'3 apples'
>>> 'dollar ' * 5
'dollar dollar dollar dollar dollar '
>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
>>> [0] * 5
[0, 0, 0, 0, 0]

Boolean operators

In Python, we have the and, or and not boolean operators. With boolean operators we perform logical operations. They are most often used with the if and while keywords.

boolean_ops.py
from itertools import product

print('a     b     | a and b  a or b  not a')

for a, b in product((True, False), repeat=2):
    print(f'{a!s:5} {b!s:5} | {a and b!s:8} {a or b!s:7} {not a}')

The program prints the truth table of the three operators. The product function generates all combinations of the two values. The and operator evaluates to True only if both operands are true; or evaluates to True if at least one of them is true; not negates its operand.

$ python boolean_ops.py
a     b     | a and b  a or b  not a
True  True  | True     True    False
True  False | False    True    False
False True  | False    True    True
False False | False    False   True

Short-circuit evaluation

The and and or operators are short-circuit evaluated: the second operand is evaluated only if the first one does not determine the result. When the first operand of and is false, the result must be false; when the first operand of or is true, the result must be true.

short_circuit.py
def check(name, value):
    print(f'evaluating {name}')
    return value


print(check('left', False) and check('right', True))
print('--')
print(check('left', True) or check('right', False))
print('--')

x = 10
y = 0

if y != 0 and x / y < 100:
    print('a small value')
else:
    print('y is zero, the division was skipped')

The check function reports when it is called. In both expressions, the right operand is never evaluated. Short-circuiting is often used as a guard: the y != 0 condition is false, so the division, which would raise a ZeroDivisionError, is skipped.

$ python short_circuit.py
evaluating left
False
--
evaluating left
True
--
y is zero, the division was skipped

Values returned by and and or

The and and or operators do not necessarily return True or False; they return one of their operands. Values such as 0, '', [], and None are considered false; most other values are true.

and_or_values.py
print(0 and 5)
print(3 and 5)
print('' or 'default')
print('Paul' or 'default')
print([] or None or 'last')

for name in ('Lucy', ''):
    print(f'Hello {name or "anonymous"}')

The and operator returns the first false operand or the last operand; or returns the first true operand or the last operand. The name or "anonymous" expression is a common way to provide a default for an empty value.

$ python and_or_values.py
0
5
default
Paul
last
Hello Lucy
Hello anonymous

Comparison operators

Comparison operators, also called relational operators, compare values.

SymbolMeaning
<strictly less than
<=less than or equal to
>greater than
>=greater than or equal to
==equal to
!=not equal to
isobject identity
is notnegated object identity
inmembership
not innegated membership

The comparison operators are not limited to numbers; strings, lists, and tuples are compared element by element. Integers and floats compare by value. Ordering values of unrelated types is not supported and raises a TypeError.

>>> 3 < 4
True
>>> 4 == 3
False
>>> 4 >= 3
True
>>> 4 != 3
True
>>> 'six' == 'six'
True
>>> [1, 2, 3] < [1, 2, 4]
True
>>> 3 == 3.0
True
>>> 'a' > 6
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    'a' > 6
TypeError: '>' not supported between instances of 'str' and 'int'

Comparing strings

Strings are compared character by character, by the Unicode code points of the characters.

compare_strings.py
print('a' < 'b')
print('a is:', ord('a'))
print('b is:', ord('b'))

print('ab' > 'aa')
print('Zebra' < 'apple')
print('Zebra'.lower() < 'apple'.lower())
print('apple' < 'apples')

The built-in ord function returns the code point of a character. When we compare 'a' and 'b', we in fact compare 97 and 98. If the first characters are equal, the next ones are compared, so 'ab' is greater than 'aa'. Uppercase letters have smaller code points than lowercase letters, so 'Zebra' comes before 'apple'; for a case-insensitive comparison, we convert both strings to lowercase. A prefix is smaller than the longer string.

$ python compare_strings.py
True
a is: 97
b is: 98
True
True
False
True

Chained comparisons

Comparisons can be chained. The expression a < b < c means a < b and b < c, except that b is evaluated only once.

chained.py
x = 7

print(1 < x < 10)
print(1 < x and x < 10)
print(0 <= x <= 5)

a = b = c = 4
print(a == b == c)

print(1 < 3 > 2)

Chaining is handy for range checks. Note that 1 < 3 > 2 is legal; it means 1 < 3 and 3 > 2 and says nothing about the relation between 1 and 2.

$ python chained.py
True
True
False
True
True

Identity operators

The identity operators, is and is not, check whether two operands are the same object. The == operator tests for equality of values.

identity.py
a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a == c)
print(a is c)
print(a is b)

b.append(4)
print(a)

print(id(a) == id(b))

val = None
print(val is None)
print(val is not None)

The lists a and c are equal but they are two distinct objects. The b variable refers to the same object as a, so appending to b changes a as well. Two objects are identical when their id values are the same. There is only one None object, so it is compared with is and is not.

$ python identity.py
True
False
True
[1, 2, 3, 4]
True
True
False

The is operator with literals

Whether two equal strings or numbers are the same object is an implementation detail. Comparing with a literal using is is a bug, and the compiler warns about it.

literal_is.py
lang = 'Python'

print(lang is 'Python')
print(lang == 'Python')

The program prints True twice, because CPython reuses the string object here, but the result could differ in another situation or implementation. The SyntaxWarning is written to standard error when the source is compiled.

$ python literal_is.py
/home/user/python/literal_is.py:3: SyntaxWarning: "is" with 'str' literal. Did you mean "=="?
  print(lang is 'Python')
True
True

Membership operators

The membership operators, in and not in, test for membership in a container, such as a string, a list, a tuple, a set, or a dictionary.

membership.py
items = ('coin', 'book', 'pencil', 'spoon', 'paper')

if 'coin' in items:
    print('There is a coin in the tuple')

if 'bowl' not in items:
    print('There is no bowl in the tuple')

print('ell' in 'Hello')

ages = {'Paul': 34, 'Lucy': 28}
print('Paul' in ages)
print(34 in ages)
print(34 in ages.values())

print(5 in range(0, 10, 2))

For strings, in tests for a substring. For dictionaries, it tests the keys; the values are checked with ages.values(). A range object checks membership arithmetically, without generating its numbers.

$ python membership.py
There is a coin in the tuple
There is no bowl in the tuple
True
True
False
True
False

Conditional expression

The conditional expression, sometimes called the ternary operator, selects one of two values based on a condition.

exp1 if condition else exp2

If the condition is true, exp1 is evaluated and its result is returned. Otherwise, exp2 is evaluated and returned.

ternary.py
age = 31
adult = 'yes' if age >= 18 else 'no'
print(f'Adult: {adult}')

vals = [3, -2, 0, 7, -5]
signs = ['positive' if v > 0 else 'zero' if v == 0 else 'negative' for v in vals]
print(signs)

The first expression decides whether a person is an adult. Conditional expressions can be nested; in the list comprehension, each value is classified as positive, zero, or negative. Deeper nesting quickly becomes hard to read; an if statement is clearer then.

$ python ternary.py
Adult: yes
['positive', 'negative', 'zero', 'positive', 'negative']

Assignment expression

The assignment expression operator :=, nicknamed the walrus operator, assigns a value to a variable and returns it. It allows assignment inside expressions, such as conditions and comprehensions.

walrus.py
import re

words = ['sky', 'blue', 'forest', 'cup', 'cloud', 'ocean']

if (n := len(words)) > 5:
    print(f'The list has {n} words')

long_words = [up for w in words if len(up := w.upper()) > 4]
print(long_words)

text = 'Order 66 was issued in 19 BBY.'
if m := re.search(r'\d+', text):
    print(f'First number: {m.group()} at {m.start()}')

We compute the length of the list once and use it both in the condition and in the message. In the comprehension, each word is converted to uppercase once and the result is used in the filter and in the output. The last if statement stores the match object and tests it in one step.

$ python walrus.py
The list has 6 words
['FOREST', 'CLOUD', 'OCEAN']
First number: 66 at 6

Bitwise operators

Decimal numbers are natural to humans; binary numbers are native to computers. Bitwise operators work with the bits of integers.

SymbolMeaning
~bitwise negation
^bitwise exclusive or
&bitwise and
|bitwise or
<<left shift
>>right shift

The bitwise negation ~x equals -(x + 1), because integers behave as if they were stored in two's complement with an infinite number of sign bits. Negating twice gives the original number. The & operator sets a bit to 1 only if both corresponding bits are 1, | if at least one of them is 1, and ^ if exactly one of them is 1. The 05b format specification shows a number as five binary digits.

>>> ~7
-8
>>> ~-8
7
>>> 6 & 3
2
>>> 6 | 3
7
>>> 6 ^ 3
5
>>> f'{6:05b} & {3:05b} = {6 & 3:05b}'
'00110 & 00011 = 00010'
>>> f'{6:05b} | {3:05b} = {6 | 3:05b}'
'00110 | 00011 = 00111'
>>> f'{6:05b} ^ {3:05b} = {6 ^ 3:05b}'
'00110 ^ 00011 = 00101'

Shift operators

The shift operators move the bits of a number to the left or to the right. Shifting left by n bits multiplies the number by 2n; shifting right by n bits divides it by 2n, rounding down.

>>> 6 >> 1
3
>>> 6 << 1
12
>>> f'{6:05b} >> 1 = {6 >> 1:05b}'
'00110 >> 1 = 00011'
>>> 1 << 10
1024
>>> -9 >> 1
-5

Bit flags

Bitwise operators are seldom used in high-level code, but they are common with flags. Each flag is a distinct bit; flags are combined with |, tested with &, removed with & ~, and toggled with ^. The enum.Flag class gives the bits readable names.

flags.py
from enum import Flag, auto


class Perm(Flag):
    READ = auto()
    WRITE = auto()
    EXECUTE = auto()


perm = Perm.READ | Perm.WRITE

print(perm)
print(Perm.WRITE in perm)
print(Perm.EXECUTE in perm)
print(perm.value, bin(perm.value))

perm &= ~Perm.WRITE
print(perm)

perm ^= Perm.EXECUTE
print(perm)

The auto function assigns the values 1, 2, and 4. The perm variable combines reading and writing; its value is 3, or 0b11. The in operator tests whether a flag is set. Then we clear the WRITE flag and toggle the EXECUTE flag with augmented assignments.

$ python flags.py
Perm.READ|WRITE
True
False
3 0b11
Perm.READ
Perm.READ|EXECUTE

Augmented assignment operators

Augmented assignment operators combine a binary operation with an assignment; i += 1 is a shorthand for i = i + 1. The available operators are:

+=   -=   *=   /=   //=   %=   **=   @=   &=   |=   ^=   >>=   <<=

There is one difference between the two forms: mutable objects such as lists are modified in place by the augmented form.

augmented.py
i = 1
i = i + 1
i += 1
print(i)

i *= 4
i -= 2
i //= 3
i **= 2
print(i)

vals = [1, 2]
alias = vals

vals += [3]
print(alias)

vals = vals + [4]
print(alias)
print(vals)

The vals += [3] statement extends the existing list, so the change is visible through the alias variable. The vals = vals + [4] statement creates a new list and binds it to vals; alias still refers to the old one.

$ python augmented.py
3
9
[1, 2, 3]
[1, 2, 3]
[1, 2, 3, 4]

Operator overloading

Operators call special methods of their operands: a + b calls a.__add__(b), a @ b calls a.__matmul__(b), -a calls a.__neg__(), and so on. By defining these methods, our classes support the operators.

overloading.py
from dataclasses import dataclass


@dataclass
class Vector:
    x: float
    y: float

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __mul__(self, k):
        return Vector(self.x * k, self.y * k)

    def __matmul__(self, other):
        return self.x * other.x + self.y * other.y

    def __neg__(self):
        return Vector(-self.x, -self.y)


u = Vector(1, 2)
v = Vector(3, 4)

print(u + v)
print(u * 3)
print(u @ v)
print(-u)

The Vector class implements vector addition, multiplication by a scalar, the dot product with the @ operator, and negation. The dataclass decorator generates the readable repr.

$ python overloading.py
Vector(x=4, y=6)
Vector(x=3, y=6)
11
Vector(x=-1, y=-2)

Operator precedence

The operator precedence tells us which operators are evaluated first. The precedence level is necessary to avoid ambiguity in expressions. Like in mathematics, multiplication has a higher precedence than addition, so 3 + 5 * 5 is 28. To change the order of evaluation, we use parentheses; expressions inside parentheses are always evaluated first.

The following list shows the operator precedence in Python, from the highest to the lowest.

(...)  [...]  {...}                    parenthesized expressions, displays
x[i]  x[i:j]  x(...)  x.attr           subscription, slicing, call, attribute
await x
**                                     power
+x  -x  ~x                             unary plus, minus, bitwise not
*  @  /  //  %                         multiplicative
+  -                                   additive
<<  >>                                 shifts
&                                      bitwise and
^                                      bitwise xor
|                                      bitwise or
in  not in  is  is not  <  <=  >  >=  !=  ==
not x                                  boolean not
and                                    boolean and
or                                     boolean or
if ... else                            conditional expression
lambda                                 lambda expression
:=                                     assignment expression

The operators on the same row have the same precedence. The power operator binds more tightly than a unary operator on its left, but less tightly than one on its right: -2 ** 2 is -4 and 2 ** -1 is 0.5.

precedence.py
print(3 + 5 * 5)
print((3 + 5) * 5)
print(2 ** 3 * 5)
print(-2 ** 2)
print((-2) ** 2)
print(not True or True)
print(not (True or True))
print(1 + 2 == 3 and 4 > 2)
print(5 & 3 == 1)
print((5 & 3) == 1)

The power operator has a higher precedence than multiplication, so 2 ** 3 * 5 is 40. The not operator binds more tightly than or. Arithmetic is done before comparisons, and comparisons before boolean operators. Unlike in C, the bitwise & operator has a higher precedence than ==, so 5 & 3 == 1 means (5 & 3) == 1.

$ python precedence.py
28
40
40
-4
4
True
False
True
True
True

Associativity

The associativity determines the order of evaluation of operators with the same precedence. Most binary operators in Python are left associative: 9 / 3 * 3 is evaluated as (9 / 3) * 3. The power operator is right associative: 2 ** 3 ** 2 means 2 ** (3 ** 2). Comparisons are not associative at all; they chain.

associativity.py
print(9 / 3 * 3)
print(100 // 10 // 2)
print(2 ** 3 ** 2)
print((2 ** 3) ** 2)

j = 0
j *= 3 + 1
print(j)

k = 2
k *= 3 + 1
print(k)

The assignment a = b = c = 0 is not an operator expression; it is a statement with several targets, all of which receive the same value. In an augmented assignment, the whole right side is evaluated first, so j *= 3 + 1 means j = j * (3 + 1); with j equal to 0, the result is 0, and with k equal to 2, it is 8.

$ python associativity.py
9.0
5
512
64
0
8

Source

Expressions – Python language reference

Operator precedence – Python language reference

In this article we have talked about operators in Python. See also Python operator module, Python walrus operator, Python and keyword, and Python lexical structure.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.