Exploring Python Operators: Beyond the Basics

Exploring Python Operators: Beyond the Basics

posted 10 min read

A. Introduction

This article is part 2 of the Basic Operators which examines Logical, Bitwise, Membership and Identity operators. This is a continuation of Part 1 which discusses Arithmetic, Comparison and Assignment operators.

Logical operators are used for evaluating conditions in control flow statements, Bitwise operators manipulate individual bits of integers, Membership operators check for the existence of a value within a sequence, and Identity operators check object identity in memory.

B. Logical Operators

These Logical operators evaluate the left and right operands which will result to either a true or false values.

1. and

The "and" operator checks if both operands are true, and if it is, then the result will be true, otherwise false.

>>> a = 100
>>> b = 20
>>> a == 100 and b == 20
True

First it evaluates if a is equal to 100 the result is True. Second it evaluates if b is equal to 20 the result is also True. Since both operands are True the final result is True. We can say that True and True is True.

Here is another example where the second operand is false.

>>> a = 100
>>> b = 20
>>> a == 100 and b < 20
False

The second operand checks if b is below 20, the answer is False because b which is 20 is not below 20. So True and False results to a False result.

Another example where the first operand is False and the second operand is True.

>>> a = 100
>>> b = 20
>>> a > 100 and b >= 20
False

The first operand evaluates to False because a which is 100 is not greater than 100. While in the second operand, it evaluates to True because b which is 20 is equal or greater than 20. So the final evaluation is False and True will result in False because both are not True.

Our last example demonstrates a scenario where both operands are false.

>>> a = 100
>>> b = 20
>>> a < 100 and b > 20
False
>>> a < 100
False
>>> b > 20
False
>>> False and False
False
>>>

So False and False will result in false.

In summary this is the truth table for and operator.

A B A and B
False False False
False True False
True False False
True True True

2. or

The or operator evaluates to true if one or both of the operands are true, otherwise false.

Let's see an example where the first operand is true and the second is false.

>>> a = 100
>>> b = 20
>>> a == 100 or b > 20
True
>>> a == 100
True
>>> b > 20
False
>>> True or False
True

The final result is True because one of the operand is True.

Here is an example scenario where the first operand is false and the second operand is true.

>>> a = 100
>>> b = 20
>>> a < 100 or b == 20
True
>>> a < 100
False
>>> b == 20
True
>>> False or True
True

The next example shows that both operands are false.

>>> a = 100
>>> b = 20
>>> a < 100 or b > 20
False
>>> a < 100
False
>>> b > 20
False
>>> False or False
False

So when both are False, the result is False.

Our last example examines what happens if both are true.

>>> a = 100
>>> b = 20
>>> a >= 100
True
>>> b <= 20
True
>>> a >= 100
True
>>> b <= 20
True
>>> True or True
True

So the final result is True if both are True.

Here is the truth table with or operator.

A B A or B
False False False
False True True
True False True
True True True

3. not

The not operator negates the given value. If the value is True, it converts it to False. And if the value is False, it converts it to True.

>>> a = True
>>> not a
False
>>> b = False
>>> not b
True
Tip: In Logical operators, it always results to either True or False values.

C. Bitwise Operators

Bitwise refers to the operations to be done on the binary bits (0 and 1). There are 6 bitwise operators that we are going to discuss. These are the "&" (and), "|" (or), "^" (xor), "~" (not), "<<" (left shift) and ">>" (right shift).

These operators are used to operate on the operands of the binary numbers. A binary number is a representation which uses only two symbols: 0 and 1. Each digit in a binary number is called a "bit," which stands for binary digit. An example of binary number is "0101". That is a 4-bit binary number.

Convert a decimal number to binary

Consider the decimal number 4, what is its binary number equivalent? Here is a manual procedure to convert it to binary.

  1. Divide the number by 2 and record the quotient and remainder.
  2. If quotient is not zero, divide it again by 2 and record the quotient and remainder.
  3. If quotient is zero record the remainder and stop the division. However if it is not zero go to step 2.

Get all the remainders starting from the last step to form the binary number with 1's and 0's.

Example

1. 4 / 2 = 2 remainder 0
2. 2 / 2 = 1 remainder 0
3. 1 / 2 = 0 remainder 1

Get all the remainder starting from step 3 to step 1.

`100`

Convert a binary to decimal

Let's convert a binary "100" to decimal number.

Starting from leftmost bit we will multiply the digit by its power of two.

0 x 2^0 = 0
0 x 2^1 = 0
1 x 2^2 = 4

Then sum the results which is 4 or 0 + 0 + 4.

1. &

The "and" operator & operates on the operands bit by bit. If both operands are 1, the result is 1, otherwise the result is 0. Let's have an example.

Here is a table with decimal integer with equivalent 4-digit binary number.

0 = `0000`
1 = `0001`
2 = `0010`
3 = `0011`
4 = `0100`
5 = `0101`
6 = `0110`
7 = `0111`
8 = `1000`
9 = `1001`

Let's solve this, calculate the result if an & operator is applied to integers 3 and 5.

3 = `0011`
5 = `0101`

    0011
&   0101
========
    0001
In the first column it is `0 & 0` which is 0.
In the second column it is `0 & 1` which is 0.
In the third column it is `1 & 0` which is 0.
In the fourth column it is `1 & 1` which is 1.

So, the final result is 0001. We can change that to decimal with the following steps.

decimal = 1 x 2^0 + 0 x 2^1 + 0 x 2^2 + 0 x 2^3
decimal = 1 + 0 + 0 + 0
decimal = 1

So 3 & 5 is equal to 1.

The truth table for Bitwise operations.

A B A & B
0 0 0
0 1 0
1 0 0
1 1 1

2. |

The "or" operator | operates bit by bit according to the following truth table.

A B A | B
0 0 0
0 1 1
1 0 1
1 1 1

Example

result = 7 | 4

`0111`
`0100`
=====
`0111`

operate vertically

0 | 0 = 0
1 | 1 = 1
1 | 0 = 1
1 | 0 = 1

decimal value for `0111`
result = 1 x 2^0 + 1 x 2^1 + 1 x 2^2 + 0 x 2^3
result = 1 + 2 + 4 + 0
result = 7
>>> 7 | 4
7
>>>

3. ^

The "xor" operator ^ performs an exclusive "or" operation on both operands bit by bit. If two corresponding bits are different, the result is 1. If two corresponding bits are the same, the result is 0.

This is the truth table for `xor`.

A B A xor B
0 0 0
0 1 1
1 0 1
1 1 0
result = 7 ^ 4

`0111`
`0100`
=====
`0011`

decimal value for `0011`
result = 1 x 2^0 + 1 x 2^1 + 0 x 2^2 + 0 x 2^3
result = 1 + 2 + 0 + 0
result = 3
>>> 7 ^ 4
3
>>>

4. ~

The "not" operator ~ executes a negation operation on its operand bit by bit. If bit is 0, it sets it to 1. And if it is 1, it sets it to 0. It is like a switch on/off.

Example with a 4-bit integer 7.

result = ~7

~ `0111`
=======
   1000

decimal value
result = 0 x 2^0 + 0 x 2^1 + 0 x 2^2 + 1 x 2^3
result = 0 + 0 + 0 + 8
result = 8

5. <<</h3> The "left shift" operator <<</code> is used to shift to the left, the bits of a binary number by a given number of positions. Example. n = 7 8-bit binary is 00000111. n The right-bit is supplied with two 0 bits and the existing bits are shifted to the left by two positions. 6. >>

The "right shift" operator >> is used to shift to the right, the bits of a binary number by a given number of positions.

Example

n = 7
4-bit binary is 0111

shift the bit 2 position to the right.
n >> 2
result = 0001

In decimal:

result = 1 x 2^0 + 0 x 2^1 + 0 x 2^2 + 0 x 2^3
result = 1 + 0 + 0 + 0
result = 1
Note: In Bitwise operations, the computation is performed bit by bit.

D. Membership Operators

Membership operators in and not in are used to test whether a value is found or not within a sequence. This sequence can be a string, dictionary, list or even a tuple.

1. in

The in operator checks if an item is in a sequence. If so it will return a boolean True otherwise False.

String example

>>> a = 'Paris'
>>> b = 'The 2024 summer olympics will be held in Paris.'
>>> a in b
True

Dictionary example

>>> cars = {'Ford': ['blind spot monitor', 'hill assist'], 'BMW': ['climate control', 'mild hybrid']}
>>> 'Ford' in cars
True

List example

>>> a = 45
>>> b = [1, 58, 69, 45, 12, 100]
>>> a in b
True
>>> 'Toyota' in cars
False

Tuple example

>>> countries = ('USA', 'China', 'France', 'Australia')
>>> 'USA' in countries
True

2. not in

The not in operator is the opposite of in. It checks if item is in a sequence and if so, it returns True if not it returns False.

List example.

>>> a = [2, 8, 4, 9]
>>> 5 not in a
True

String example.

>>> a = ['basketball', 'cricket', 'soccer']
>>> 'baseball' not in a
True

Tuple example.

>>> a = (8, 9, 1, 3)
>>> 8 not in a
False

E. Identity Operators

The Identity is and is not operators are used to check if two variables refer to the same object in memory. The is operator returns True if the memory addresses of the two variables are the same, otherwise it returns False. The is not operator is the negatiion is.

1. is

The is operator checks if memory addresses of two operands are the same. If so it returns True otherwise False.

>>> a = 50
>>> b = 100
>>> a is b
False

Let's check the address of a and b.

>>> id(a)
140717562022216
>>> id(b)
140717562023816

Since the address in memory is different, the result is False.

2. is not

The is not operator checks if memory addresses of two operands are different. If so it returns True otherwise False.

>>> a = 'basketball'
>>> b = 'soccer'
>>> a is not b
True

The result is True because the addresses of a and b are different.

FAQ 1. How to get the memory address of an object for `is` and `is not` operators?
Answer: Use the id(object) function.

F. Summary

Logical operators (and, or, not) evaluate operands to produce true or false outcomes. The "and" results in true only if both are true, "or" is true if either operand is true.

Bitwise operators work on binary bits. Examples include "and" (&), "or" (|), "xor" (^), "not" (~), "left shift" (<), and "right shift" (>>). They manipulate binary representations of numbers.

Membership operators (in, not in) determine if a value is within a sequence (e.g., string, list, tuple). 'in' returns true if found, 'not in' returns true if not found.

Identity operators (is, is not) check if variables refer to the same memory location. 'is' returns true if they do, 'is not' returns true if they don't.

It would be interesting to study further especially on operator precedence.

For further reading have a look on Python's Syntax which outlines the fundamental grammar of the language. And Python variables and data types which introduces how to use variables and what data types are.

If you read this far, tweet to the author to show them you care. Tweet a Thanks
Thank you for the continuation of this series. Truly these python operators are the basic powers of learning and understanding how logic work in python programming language. Good one.

More Posts

Basic operators in Python

Ferdy - May 19, 2024

Python Variables and Data Types

Ferdy - Mar 23, 2024

Python Syntax

Ferdy - Mar 5, 2024

Testing the performance of Python with and without GIL

Andres Alvarez - Nov 24, 2024

Python on the web - High cost of synchronous uWSGI

Vivek Sahu - Apr 30, 2024
chevron_left