# How to use Python operators

## What are Python operators and how do they work?

**character for an operation**. Operators are usually used to link several operands to form a new value. The application of an operator to a single operand modifies it.

The simplest example of Python operators would probably be to join two numbers using the

**addition operator**, which is a plus sign between the numbers. Python evaluates the expression and returns the corresponding value:

`1 + 1`

**combination of operators and operands**results in an expression:

`1 + 1 == 2`

### What are the different types of Python operators?

**operate on different types of operands**and return a certain type of results. Below is an overview of the different types of Python operators:

Classes of Python operators | Explanation | Operands | Result | Operators at a glance |

Arithmetic operators | Combine two numbers to form a new number | Numbers | Number | +, -, *, /, //, %, **, @ |

Comparison operators | Compare two expressions with each other | Expressions | Boolean | <, >, ==, !=, <=, >= |

Logical operators | Combine expressions in a Boolean context | Expressions | Last evaluated expression / Boolean | and, or, not |

Bitwise operators | Manipulate integers as binary sequences | Numbers | Number | <<, >>, &, |, ^, ~ |

Assignment operators | Assign value to a name | Lvalue, Rvalue | - / Evaluated expression | =, :=, +=, -=, *=, etc. |

Identity operators | Determine whether two names refer to the same object | Objects | Boolean | is, is not |

Conditional operator | Returns one of two values depending on a condition | Expression, condition, alternative | Expression / Alternative | ... if ... else ... |

Set operators | Link two sets / Compare sets | Quantities | Quantity / Boolean | &, |, ^, -, <, >, <=, >= |

Membership operators | Testing whether an iterable contains a specific object | Object, Iterable | Boolean | in, not in |

Concatenation operator | Chained sequences | Strings / Lists / Tuples | String / List / Tuple | + |

Index and slice operators | Return one or more elements of an iterable | Iterable, Index / Slice | String / List / Tuple | [], [::] |

**how many operands an operator combines**. “Binary” operators with two operands are used in most cases. There are also some “unary” operators with only one operand, as well as a “ternary” operator which links three operands:

Operator arity | Number of operands | Example |
---|---|---|

Unary | One operand | not single_value |

Binary | Two operands | left_operand + right_operand |

Ternary | Three operands | some_value if condition else other_value |

### What is note operator precedence?

**point before dash calculation**”. Just to remind you, the expression

*3 * 8 + 2*is interpreted as

*(3 * 8) + 2*,

*not*

*3 * (8 + 2)*.

*As for the plus sign and the multiplication sign, there are precedence rules for all Python operators. Below is an example of an expression with the logical operators “and”, “or” and “not”:*

```
if is_user and is_user_logged_in or is_admin and not login_blocked:
...
```

**not to rely on a perfect understanding of implicit rules**. You should use explicit braces to clarify how the expression’s terms belong together:

```
if (is_user and is_user_logged_in) or (is_admin and not login_blocked):
...
```

**same terms grouped differently**result in a different statement:

```
if (is_user and is_user_logged_in or is_admin) and not login_blocked:
...
```

### What are overloaded operators, Dunder methods and Python operator functions?

**for more than one operation**. A prominent example is the plus sign. The plus sign acts as both an addition operator for numbers and a concatenation operator for concatenating sequences such as strings and lists. We add two numbers with the addition operator:

`8 + 3 == 11`

**two strings**using the same operator:

`"Walter" + "White" == "WalterWhite"`

**lists**with the plus operator:

`['Jack', 'Jim'] + ['John'] == ['Jack', 'Jim', 'John']`

**overloaded operators**”, which happen when one and the same operator perform different operations depending on the operands’ data type.

How do overloaded operators work in Python? An operator and its operands are interpreted as a

**cue to a corresponding function**. The first operand’s Dunder method is enabled, which receives the other operands as arguments. “Dunder” stands for “double underscore”. Therefore, the plus operator corresponds to the

*__add__()*Dunder method. Objects which implement an

*__add__()*method can be linked with the plus operator. It is up to the object what constitutes the link exactly.

In addition to the Dunder methods, the operator module contains

**functions which enclose the Python operators’ functionality**. For example, “operator.add(a, b)” enables the Dunder method

*a.__add__(b)*, which is

*equivalent to the expression*

*a + b*. We’ll list the operator function for each operator when possible throughout the rest of the article. The name of the operator function corresponds to the name of the appropriate Dunder method. You can use this table as a reference for implementing your own operator functionality:

Python operator | Operator function | Dunder method |
---|---|---|

a + b | operator.add(a, b) | a.__add__(b) |

**infix notation**which inserts the operator between the operands, while the functional style uses the prefix notation. Both notations are equivalent:

Notation | Use | Example |
---|---|---|

Infix | Operators | a + b |

Prefix | Functions | + a b / add(a, b) |

**define two numbers and add them**to the operator, the operator function and the corresponding Dunder method:

```
import operator
a = 42
b = 69
assert a + b == operator.add(a, b) == a.__add__(b)
```

```
import operator
assert 'Py' + 'thon' == 'Python'
assert operator.eq(operator.add('Py', 'thon'), 'Python')
```

## An overview of Python operators

**eleven different Python operator classes**.

### Arithmetic operators

**arithmetic operators operate on numbers**to create a new number. All of these are binary operators except for the unary plus or minus. An overview is outlined below:

Python operator | Meaning | Operator function | Example |
---|---|---|---|

+ | Addition / unary plus | add(a, b) / pos(a) | 5 + 3 == 8 / +8 == 4 + 4 |

- | Subtraction / unary minus | sub(a, b) / neg(a) | 7 - 2 == 5 / -4 == 2 - 6 |

* | Multiplication | mul(a, b) | 2 * 3 == 6 |

/ | “Real” Division | truediv(a, b) | 8 / 2 == 4.0, 7 / 2 == 3.5 |

// | Integer division to next lower integer | floordiv(a, b) | 8 // 2 == 4, 7 // 2 == 3 |

% | Modulus: Integer division’s remaining amount | mod(a, b) | 8 % 2 == 0, 7 % 2 == 1 |

** | Exponentiation | pow(a, b) | 2 ** 3 == 8, 10 ** -1 == 0.1 |

@ | Matrix multiplication | matmul(a, b) | - |

**modulus operation**is used by default to determine whether a number is even. This is because an even number divided by two has a remainder of zero. We define a corresponding Python function with the modulus operator:

```
def is_even(number):
return number % 2 == 0
# test
assert is_even(8) and not is_even(7)
```

**multiplication**requires a package such as NumPy.

### Comparison operators

**how two elements can be ordered with respect to each other**. They give a Boolean result and are used especially for sorting algorithms:

Python operator | Meaning | Operator function | Example |
---|---|---|---|

< | Less than | lt(a, b) | 3 < 1, 'a' < 'z' |

> | Greater than | gt(a, b) | 4 > 2, 'z' > 'a' |

== | Equals | eq(a, b) | 'a' == 'a' |

!= | Not equals | ne(a, b) | 1 ! = 2, 'Jim' != 'Jack' |

<= | Smaller equals | le(a, b) | 9 <= 10, 10 <= 10 |

>= | Greater equals | ge(a, b) | 11 >= 10, 10 >= 10 |

### Logical operators

**link multiple operands following Boolean logic**. As a result, both operators return the last evaluated object. Python’s logical “not” operator interprets an object in the Boolean context and negates its truth value:

Python operator | Meaning | Operator function | Example |
---|---|---|---|

and | Logical AND | no direct correspondence | True and False == False, 'name' and ... == ... |

or | Logical OR | no direct correspondence | False or True == True, a = '' or 'Default'; assert a == 'Default'. |

not | Denial | not_(a) | not True == False |

**effect of logical operations**at truth tables. Below is the logical “AND”:

and | True | False |

True | True | False |

False | False | False |

or | True | False |

True | True | True |

False | True | False |

**following objects evaluate to false in the Boolean context**and are referred to as “falsy”:

Object | Explanation |
---|---|

False, None | Constants which are False according to the definition |

0, 0.0, Decimal(0), Fraction(0, 1), etc. | Number which represents zero |

'', (), [], {}, set(), range(0), etc. | Empty sequence or collection |

### Bitwise operators

**operate on integers, which are interpreted as bit sequences**. They are all binary operators except for the bitwise “NOT” operator:

Python operator | Meaning | Operator function | Example |

<< | Shift bit sequence to the left | lshift(a, b) | 5 << 3 == 5 * 2 ** 3 |

>> | Shift bit sequence to the right | rshift(a, b) | 1 >> 1 == 0, 8 >> 1 == 4 |

& | Combine two bit sequences by “AND” | and_(a, b) | `` |

| | Concatenate two bit sequences by “OR” | or_(a, b) | `` |

^ | Linking two bit sequences using “XOR” | xor(a, b) | `` |

~ | Invert bit sequence with “NOT” | invert(a) | `` |

**suitable for optimized mathematical operations**. The left shift corresponds to a multiplication by a power of two:

Expression | 23 = 8 | 22 = 4 | 21 = 2 | 20 = 1 | Decimal |

b = 6 | 0 | 1 | 1 | 0 | 6 |

b << 1 | 1 | 1 | 0 | 0 | 12 |

b >> 1 | 0 | 0 | 1 | 1 | 3 |

**table of the individual bits**to illustrate the bitwise “AND”, “OR”, and “NOT” operations. The operations are applied to a number in binary representation using a bit mask:

Expression | 23 = 8 | 22 = 4 | 21 = 2 | 20 = 1 | Decimal |

bits = 6 | 0 | 1 | 1 | 0 | 6 |

mask = 5 | 0 | 1 | 0 | 1 | 5 |

bits & mask | 0 | 1 | 0 | 0 | 4 |

bits | mask | 0 | 1 | 1 | 1 | 7 |

bits ^ mask | 0 | 0 | 1 | 1 | 3 |

**NOT” operator inverts a bit sequence**. This turns every 1 into a 0 and vice versa. Furthermore, the number’s sign is reversed:

Expression | 23 = 8 | 22 = 4 | 21 = 2 | 20 = 1 | Decimal |

b = 6 | 0 | 1 | 1 | 0 | 6 |

~ b | 1 | 0 | 0 | 1 | -7 |

### Assignment Operators

**bind a value to a variable name**. There is the newer “walrus” operator in addition to the assignment statement, which allows assignment within an expression. There are also several extended assignment statements which combine an assignment with another operation:

Python operator | Meaning | Operator function | Example |
---|---|---|---|

= | Assignment statement | no direct correspondence | name = 'Walter' |

:= | Assignment expression (“walrus” operator) | no direct correspondence | [ half for x in range(10) if (half := x / 2) < 5 ] |

+= | Advanced addition assignment | iadd(a, b) | x = 1; x += 4; assert x == 5 |

**general pattern using the extended concatenation assignment as an example**. A code which appends another part to an existing string is shown first:

```
name = 'Walter'
name = name + 'White'
assert name == 'WalterWhite'
```

```
name = 'Walter'
name += 'White'
assert name == 'WalterWhite'
```

### Identity Operators

**whether two variables refer to the same object in storage**. Object identity contrasts with object equality, which is tested by the Python comparison operator “==”. The “is” in Python is similar to JavaScript’s strict equality operator “===”. Python also has a negated identity test with the “is not” operator:

Python operator | Meaning | Operator function | Example |
---|---|---|---|

is | Identity Test | is_(a, b) | a = 42; b = a; assert a is b |

is not | Negated Identity Test | is_not(a, b) | assert [42] is not [42] |

**both variables point to the same object in storage**:

```
# assign value to name
a = [42]
# reference existing object
b = a
# if this holds
assert a is b
# so will this
assert a == b
```

**references to independent objects in memory**in the example below. Although the objects are the same, they are distinct. The is operator will return false in this case:

```
# assign the same value to different names
a = [42]
b = [42]
# `a`, `b` are two different objects
assert a is not b
# that contain the same value
assert a == b
```

### Conditional operator

**distinguish between two possible values in assignments**. It is also known as a ternary operator, as the conditional operator combines a condition and two expressions.

Python operator | Meaning | Operator function | Example |
---|---|---|---|

... if ... else ... | Conditional expression | no direct correspondence | name = 'Jim' if age == 42 else 'Jack' |

**unit for a temperature measurement**depending on the chosen measurement system:

```
if system == 'metric':
unit = 'C'
else:
unit = 'F
```

**using the conditional operator**:

`unit = 'C' if system == 'metric' else 'F'.`

### Set operators

**sets as a composite data type**by default. Overloaded operators are defined for the usual set operations:

Python operator | Meaning | Operator function | Example | ||
---|---|---|---|---|---|

& | Union of two sets | and_(a, b) | {'a', 'b'} & {'a', 'c'} == {'a'} | ||

Intersection of two sets | or_(a, b) | {'a', 'b'} | {'a', 'c'} == {'a', 'c', 'b'} | ||

^ | Form symmetrical difference of two sets | xor(a, b) | {'a', 'b'} ^ {'a', 'c'} == {'c', 'b'} | ||

- | Difference of two sets | sub(a, b) | {'a', 'b'} - {'a'} == {'b'} | ||

> | Tests if quantity is a true superset | gt(a, b) | assert {'a', 'b'} > {'a'} | ||

>= | Tests if a set is a superset | ge(a, b) | assert {'a'} >= {'a'} | ||

< | Tests if quantity is a true subset | lt(a, b) | assert {'a'} < {'a', 'b'} | ||

<= | Tests if quantity is a subset | le(a, b) | assert {'a'} <= {'a'} |

### Membership Operators

**object is**

**included in a collection**.

Python operator | Meaning | Operator function | Example |
---|---|---|---|

in | Tests whether an object is contained in an iterable | contains(a, b) | 'y' in 'Python' |

not in | Negation of the in operator | not contains(a, b) | 'x' not in 'Python' |

**iterables**and use an

**equality check**to determine if the target object is in the collection:

```
'Py' in 'Python'
'Px' not in 'Python'
'Jack' in ['Jim', 'Jack']
```

```
def my_in(target, collection):
for element in collection:
if element == target:
return true
return False
# test
word = 'Python'
letter = 'y'
assert (my_in(letter, word)) == (letter in word)
```

### Concatenation operator

**concatenate sequences of the same type**. The operator symbol is the plus sign.

Python operator | Meaning | Operator function | Example |
---|---|---|---|

+ | Links two sequences | add(a, b) | ['Jim'] + ['Jack', 'John'] |

**two strings, two lists and two tuples**:

```
assert "Walter" + "White" == 'WalterWhite'
assert ['a', 'b'] + ['c'] == ['a', 'b', 'c']
assert ('q', 'r') + ('s', 't') == ('q', 'r', 's', 't')
```

```
site_title = 'Welcome'
print('<h1>' + site_title + '</h1>')
```

**PHP**:

```
$siteTitle = 'Welcome';
echo '<h1>' . $siteTitle . '</h1>';
```

### Index and slice operators

**extract**a specific element of a collection. The slice operator is used to extract a subsequence.

Python operator | Meaning | Operator function | Example |
---|---|---|---|

iterable[index] | Returns the element of an iterable located under the index. | getitem(iterable, index) | 'Python'[1] == 'y' |

sequence[start:stop:step] | Returns a slice of a sequence | getitem(iterable, slice(start, stop, step)) | 'Python'[0:1] == 'Py', 'Python'[0:-1:2] == 'Pto' |

*__getitem__()*method. This is enabled with either a numeric index or a slice object:

```
names = ['Jim', 'Jack', 'John']
names[0] == names.__getitem__(0)
names[0:2] == names.__getitem__(slice(0, 2))
```

**subsequence to be extracted**without using a Python for-loop or Python while-loop. This saves programmers from writing code in the following form:

```
word = 'Python'
start, stop, step = 0, 5, 2
index, substring = start, ''
while index in range(start, stop, step):
substring += word[index]
index += step
# test
assert substring == word[start:stop:step]
```

Contents

### Related articles

### Boolean operators: Smart searching in Google and other search engines

Boolean operators work in almost all search engines. They are named after English mathematician George Boole. As online search tools have evolved, further operators have been added to make online searches more efficient. How do these search operators work? And how can you use and…

### Docker commands

Docker commands are used to control the Docker engine on a local host. When entered via the command line, they are translated into API calls to the Docker daemon. Docker commands can be used to manage images, containers, and volumes. If you tend to work with the software…

### netstat commands for Windows, Linux, and Mac at a glance

You can use the netstat network tool in Windows as well as in macOS and Linux via the respective command line program. Depending on the system you are working with, you only need the appropriate netstat commands to check the status of active and inactive connections. We have…

### What are the most important C++ operators?

C++ operators are extremely useful when writing programs in the object-oriented programming language. In this article, we’ll go over what they are, what operator precedence is, and how to overload C++ operators. Additionally, we’ll cover the different C++ operator categories and…

### Java Operators

If you use Java as your programming language of choice, sooner or later you will come across Java operators, which can be used to compare values. Our article explains what these operators are and how you can use them. We’ll take a look at arithmetic, Boolean and bitwise Java…

### How to install Python on Windows, Linux and macOS

If you want to learn to program with Python or use the scripting language to develop an application, you must first install the appropriate version on your operating system. Find out what the requirements are for this, where you can download the necessary program packages and how…