Python operators - Python

Next, I list the available Python operators in their precedence order. I also provide some specific details about some of them.

1. (), [], {}
2. object
3. object[i], object[l:r], object.attribute, function()

The .(dot) operator is used to access attributes and methods of a variable (object). In the following example, the dot enables the object t to access its method append.

4. +x, -x, ~x

These are bitwise operators.

5. x**y
6. x*y, x/y, x%y
7. The % (modulo) operator lets you know whether a number is divisible by another number. For example, if a % b == 0, a is divisible by b.

8. x+y, x-y
9. x<<y, x>>y
10. These operators provide shifting operations. The <<operator ensures left shifting (at bit level),and the >>operator ensures right shifting (at bit level).

>>> x = 2 # the binary representation is 0010
>>>x<< 1 # the binary representation will be 0100
4
11. x& y
12. The bitwise AND operator

13. x ^ y
14. The bitwise XOR (exclusive OR) operator

15. x | y
16. The bitwise OR operator

17. <, <=, >, >=, ==, !=, <>, is, is not, in, not in
18. The operators in and not in work only with lists. Another aspect of this group is that there's an important difference between the == operator and the = assigning symbol. ischecks whether two variables refer to the same object. On the other hand, is not checks whether two variables don't refer to the same object.

The == operator ensures equality testing, whereas = assigns a value to a variable.

Tip Keep in mind that x = y doesn't create a new copy of y. Instead, it makes a reference to it.

However, if later you define x=x+1, a new reference for x is created, and then they become different because the operator has created a new object.

Note that x.append(5) doesn't create a new reference to x because x changes itself withoutusing a = operator.

19. not
20. and
21. or, lambda args:expr

As a good programmer, you need to know that logical operations can also be emulated by using if statements. Note that the return values are not limited to zeros and ones.

The operation a and b can be written as the following:

The operation a or b can be written as the following:

The operation not a can be written as the following:

Augmented Assignment

Starting with Python 2.0, the language also implements a full set of augmented assignment operators.

That includes: +=, -=, *=, /=, %=, **=, &=, |=, ^=, »=, and «=
For example, instead of saying x = x+1, you can choose to say x += 1
Python Topics