# Mastering Python Operations (Part 3)

In our preceding blog posts, we delved into the concepts of Relational and Logical operators. Throughout three blogs, we meticulously discussed various operators. To gain an in-depth understanding of these operators, we kindly encourage you to explore our earlier blog entries.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><a target="_blank" rel="noopener noreferrer nofollow" href="https://blog.bytescrum.com/mastering-python-operators-part-1" style="pointer-events: none">https://blog.bytescrum.com/mastering-python-operators-part-1</a> <a target="_blank" rel="noopener noreferrer nofollow" href="https://blog.bytescrum.com/mastering-python-operators-part-2" style="pointer-events: none">https://blog.bytescrum.com/mastering-python-operators-part-2</a></div>
</div>

With this foundation, we now present the concluding blog in our series on [operators](https://www.allwealthinfo.com/web?q=best+online+python+courses&o=1672412&cid=20228060390&agid=150296860952&utm_source=google&gclid=Cj0KCQjw0bunBhD9ARIsAAZl0E2XN-mCivNB_d5jiFXWA5t0iUlLocQbOKWhy503BJed3PjG9O6NnL8aAn33EALw_wcB&qo=semQuery&ag=fw10&tt=rmd&ad=semA&akid=awi-20228060390-150296860952&an=google_s). We invite you to seamlessly transition from our previous discussions and join us in further exploring the intricacies of [operators](https://my.newtonschool.co/register?hsa_acc=6133007348&hsa_cam=18274924962&hsa_grp=141772894260&hsa_ad=620608064395&hsa_src=g&hsa_tgt=aud-1606574140471%3Akwd-300539935636&hsa_kw=python+science&hsa_mt=b&hsa_net=adwords&hsa_ver=3&gad=1&gclid=Cj0KCQjw0bunBhD9ARIsAAZl0E0bD_BR-BBiBRNFzihghucMNyYmBQNERZmqSyGCry_A-3SQ7igw1lUaAn1IEALw_wcB&redirect=true&type=apply-form&hash=gos2ze8seake) in this final installment. Your continued interest and engagement are greatly appreciated.

## **Bitwise Operators**

When [operating](https://www.coursera.org/articles/what-is-python-used-for-a-beginners-guide-to-using-python) on individual bits of numeric values, [bitwise](https://www.digitalocean.com/community/tutorials/python-bitwise-operators) [operators](https://www.koenig-solutions.com/python-intro-certification-training-course?keyword=intro%20to%20python%20online%20course&device=c&utm_source=google&utm_medium=cpc&utm_device=c&utm_campaign=Chennai_-_India-adgroup-Introduction_to_Python_Chennai_-_India&gclid=Cj0KCQjw0bunBhD9ARIsAAZl0E1UrWPjwcfKZsHCtpsx8vuD3WaleVkpvC-WMnxcCCabhrwPInCgTCcaAiCaEALw_wcB) work at the binary level. They are important in low-level programming and certain instances of data manipulation while being less often employed.

On binary representations of integers, these operators do out [operations](https://www.datacamp.com/blog/what-is-python-used-for).

* [Bitwise](https://wiki.python.org/moin/BitwiseOperators) **AND** [**Operator**](https://www.programiz.com/python-programming/operators)
    
* [**Bitwise**](https://www.tutorialspoint.com/python/bitwise_operators_example.htm) **OR** [**Operator**](https://www.scaler.com/topics/bitwise-operator-in-python/)
    
* [**Bitwise**](https://www.geeksforgeeks.org/python-bitwise-operators/) **XOR** [**Operator**](https://www.futurelearn.com/info/blog/what-is-python-used-for)
    
* [**Bitwise**](https://realpython.com/python-bitwise-operators/#left-shift) **NOT** [**Operator**](https://www.python.org/about/apps/)
    
* **Left shift** [**Operator**](https://codeinstitute.net/global/blog/what-is-python-used-for/)
    
* **Right shift** [Operator](https://www.simplilearn.com/what-is-python-used-for-article)
    

### **Bitwise AND** [**Operator**](https://www.codecademy.com/resources/blog/what-is-python-used-for/) **(&)**

The bitwise **AND** operation is a crucial operation in computer programming, comparing binary values using the '**&**' sign, enabling efficient permission checks and bitwise manipulations.

### How it works

* The outcome bit is set to **1** if both of the [operand](https://www.toppr.com/guides/computer-science/introduction-to-python/variables-expressions-and-statements/operators-and-operands-in-python/#:~:text=Operators%20refer%20to%20special%20symbols,%2C%20relational%2C%20and%20logical%20operations.)'s corresponding bits are **1**. The outcome bit is set to **0** if any of the relevant [operand](https://realpython.com/python-operators-expressions/) bits are **0**.
    

### **Example 1**

Let's look at an instance where you have a collection of data that represents various permissions and you want to utilize bitwise **AND** to determine whether or not a certain permission is authorized.

Let's say you have the enumerated authorization flags.

* **Read: 0001**
    
* **Input: 0010**
    
* **Output: 0100**
    
* **Delete: 1000**
    

Confirm the user's read and write permissions using binary integer representation, indicating allowed(**1**) or not(**0**).

**Let's assume that the user has the following permissions: 0011**

You may use the bitwise **AND** operation to determine whether the user has "**Read**" and "**Write**" permissions.

```markdown
  0011 (User's permissions)
& 0010 (Write permission flag)
-----------
  0010
```

The user does have the "**Write**" permission, as shown by the result of **0010**. They lack the "**Read**" permission, though, as the "**Read**" matching bit is set to **0**.

### **Bitwise OR** **Operator(**|**)**

Bitwise **OR** is a common technique in programming to efficiently manage various settings, flags, or attributes using binary representations, resulting in a compact set of options.

### How it works

* The outcome bit is set to **1** if any of the corresponding bits in the [operand](https://www.geeksforgeeks.org/python-operators/)s is **1**. The outcome bit is set to **0** if both of the [operands](https://www.tutorialspoint.com/python/python_basic_operators.htm)' corresponding bits are **0**.
    

### **Example 2**

Let's say you have the enumerated authorization flags.

* **Read: 0001**
    
* **Write: 0010**
    
* **Execute: 0100**
    
* **Delete: 1000**
    

A user should be given "**Read**" and "**Write**" access. To combine these two flags, utilize the [bitwise](https://medium.com/@shashankmohabia/bitwise-operators-facts-and-hacks-903ca516f28c) **OR** technique.

```markdown
  0001 (Read permission flag)
| 0010 (Write permission flag)
-----------
  0011 (Read and Write combined)
```

The outcome, **0011**, denotes permissions with both "**Read**" and "**Write**" capabilities.

User "**Read**," "**Write**," and "**Execute**" permissions. You can use the [bitwise](https://www.geeksforgeeks.org/bit-tricks-competitive-programming/) OR operation

```markdown
  0011 (Read and Write combined)
| 0100 (Execute permission flag)
-----------
  0111 (Read, Write, and Execute combined)
```

The outcome is **0111**, which is the sum of the three permits.

### **Bitwise XOR** **Operator(^)**

Another essential operation in computer programming that works on the individual bits of binary integers is the bitwise **XOR** (exclusive **OR**) operation. The bitwise XOR operation between two binary values is done using the symbol "**^**"

*The bitwise* ***XOR*** *technique is used to toggle or flip specific bits in a binary integer.*

### How it works

* The result bit is set to **1** if the matching [operand](https://runestone.academy/ns/books/published/fopp/SimplePythonData/Operators.html) bits vary (one is **0** and the other is **1**).
    
* The outcome bit is set to **0** if the corresponding [operand](https://runestone.academy/ns/books/published/thinkcspy/SimplePythonData/OperatorsandOperands.html) bits are the same (either both **0**s or both **1**s).
    

### **Example 3**

This example shows how to efficiently manipulate bits in programs by selectively flipping or toggling particular bits in a binary representation using the bitwise **XOR** function.

```markdown
  00110110 (Original number)
^ 00100100 (Mask for toggling 3rd and 6th bits)
-----------
  00010010 (Result after toggling)
```

To toggle the third and sixth bits, create a mask with all bits set to **0**, and only toggle the desired bits.

### **Bitwise NOT** [**Operator**](https://www.freecodecamp.org/news/operators-in-python-how-to-use-logical-operators-in-python/)**(**~**)**

*The bitwise NOT operation or bitwise complement uses the symbol* ***'~****'.*

### How it works

In the [operand](https://www.programiz.com/python-programming/operators), each **1**\-bit is converted to a **0**\-bit, and vice versa for each **0**\-bit.

### **Example 4**

Let's use the binary number **00101011** as an example and execute a bitwise **NOT** operation on it.

Original number: **11011001**

Mask: **11101111** (bits **2** and **5** cleared, other bits set to **1**)

```markdown
#Original:  00101011
#Bitwise NOT: 11010100

  11011001 (Original number)
& 11101111 (Mask)
-----------
  11001001 (Result after clearing bits)

Bitwise NOT of Mask: 00010000
```

Create a mask with desired bits set to 0, and all other bits set to 1, and perform a bitwise AND operation between the original number and the mask to clear the second and fifth bits.

### **Left shift** [**Operator**](https://makemeanalyst.com/python-programming/operators-and-expressions/)**(**&lt;&lt;**)**

Left shift is a bitwise operation that moves the bits of the left [operand](https://www.javatpoint.com/python-operators) to the left by a specific number of places. It is a common optimization technique in low-level programming.

### How it works

* The right [operand](https://www.w3schools.com/python/python_operators.asp)'s number shifts each bit in the left [operand](https://www.simplilearn.com/tutorials/python-tutorial/operators-in-python), deleting any moved bits past the leftmost position and pushing zeros from the right side.
    

### **Example 5**

To multiply a binary number by a power of 2, use the left shift operation. For example, to multiply **00101010** by **4** (a power of **2**), left-shift the bits by **2** positions. Then, perform a bitwise **AND** between the original number and mask.

```markdown
Original:     00101010
Left Shift 2: 10101000
```

The left shift operation results in **10101000**, representing the original number multiplied by 4. It can also be used for multiplication by larger powers of **2**, like multiplying by **8** (which is **2^3**), you would shift the bits by **3** positions.

```markdown
Original:     00101010
Left Shift 3: 10100000 #the left shift operation produces the number 10100000, which is the original number times eight
```

### **Right shift** [**Operator**](https://www.codingninjas.com/studio/library/python-operators)**(&gt;&gt;)**

The right shift operation, denoted by the symbol (**&gt;&gt;**), is a bitwise operation that moves the bits of the left [operand](https://www.scaler.com/topics/python/operators-in-python/) to the right by a certain number of places.

### How it works

* The left [operand](https://docs.python.org/3/library/operator.html) of a number is shifted to the right by the number of positions specified in the right [operand](https://mindmajix.com/python/basic-operators-in-python).
    
* Unsigned numbers have zeros shifted in from the left side, while signed numbers have arithmetic or logical right shifts depending on the programming language and system architecture.
    

### Example 6

To extract the green component from a color representation with red, green, and blue components, **right-shift** the color by **8** positions, discarding the least significant bits. This demonstrates the use of **right-shift** operations in conjunction with other bitwise operations to manipulate and extract specific fields from binary data structures.

To eliminate the least important **8** bits (the blue component), move the entire color to the right by 8 places.

```yaml
Original Color:  RRRRRRRRGGGGGGGGBBBBBBBB
Right Shift 8:   00000000RRRRRRRRGGGGGGGG
```

The green component is at the least significant **8** bits of the result, extracted by bitwise **AND** operation with mask set to **1**.

```yaml
00000000RRRRRRRRGGGGGGGG (Result after right shift)
```

The result of the bitwise **AND** operation is the extracted green component of the color.

## [**Membership Operator**](https://www.tutorialspoint.com/python/membership_operators_example.htm)**s**

[Membership operator](https://www.scaler.com/topics/membership-operator-in-python/)s improve efficiency in searching and filtering by determining if a specific value is present in a sequence (such as a list, tuple, or string).

* **In Operator**
    
* **Not In**
    

### IN [Operator](https://www.aipython.in/python-operator/)

*Returns* ***True*** *if a value is found in the sequence*

To determine if a certain value is contained in a sequence, such as a list, tuple, string, or other iterable data types, programmers frequently use the in [operator](https://www.w3schools.com/python/python_operators.asp). The in-[operator](https://www.geeksforgeeks.org/python-operators/) is quite handy for searching for specific values within sequences and is commonly used for decision-making and conditional checks in programming.

### How it works

The **in-**[**operator**](https://www.programiz.com/python-programming/operators) returns True if the value on the left side of the [operator](https://www.tutorialspoint.com/python/python_operators.htm) is present in the sequence on the right side. The [operator](https://www.javatpoint.com/python-operators) returns **False** if the value is missing from the sequence.

### **Example 7**

list of usernames, and you want to use the in operator to see if a certain username is present in the list.

```python
# List of usernames
usernames = ["Sanjay", "Amit", "Shashank", "Jhanavi", "Preeti"]

# Username to search for
search_username = "Sanjay"

# Check if the username exists in the list
if search_username in usernames:
    print(f"The username '{search_username}' exists.")
else:
    print(f"The username '{search_username}' does not exist.")
```

```python
The username 'Sanjay' exists.
```

The result will be a list of usernames, and you want to use the in operator to see if a certain username is already in the list if you alter **search\_username** to a username that isn't already in the list, like '**Akhila**'.

```python
The username 'Akhila' does not exist
```

### Not In [Operator](https://realpython.com/python-operators-expressions/)

*Returns True if a value is not found in the sequence*

To detect whether a certain value is absent from a sequence, such as a list, tuple, string, or other iterable data types, use the **not-in** [operator](https://mindmajix.com/python/basic-operators-in-python).

* The **not-in** [operator](https://www.scaler.com/topics/python/operators-in-python/) returns **True** if the value on the left side of the [operator](https://www.crio.do/projects/category/python-projects/?utm_source=adwords&utm_medium=Projects&utm_campaign=Python&utm_term=coding%20projects%20in%20python&gad=1&gclid=Cj0KCQjw0bunBhD9ARIsAAZl0E0X1E6yOo-XadcOHntU6qA-JN9yyZ87OyEp4Zuisr2AyMMIqNi7VU8aArnGEALw_wcB) cannot be found in the sequence on the right side.
    
* The [operator](https://www.guvi.in/zen-class/python-course/?utm_source=Google&utm_medium=Search&utm_campaign=Mini-Course-Python-Feb-22&utm_network=g&utm_device=c&utm_keyword=python&gad=1&gclid=Cj0KCQjw0bunBhD9ARIsAAZl0E0V2uAQjcnwFbmZwdNcFp4KCVnR0frYfUEG_z0dJaqauWxDZ4DvLSEaAp4tEALw_wcB) returns **False** if the value is present in the sequence.
    

### **Example 8**

When building a restaurant reservation system, you have a tuple that represents the available tables. You want to be sure that you can make a reservation for a certain table.

```python
# Tuple representing available tables
available_tables = ("Table 1", "Table 2", "Table 3", "Table 4", "Table 5")

# Check if a table is not available for reservation
table_to_reserve = "Table 6"
if table_to_reserve not in available_tables:
    print(f"{table_to_reserve} is not available for reservation.")
else:
    print(f"{table_to_reserve} is available for reservation.")
```

```python
Table 6 is not available for reservation.
```

The **not-in operation** returns True, indicating that "**Table 6**" is not a part of the **available\_tables** tuple and so cannot be reserved.

## **Identity** [**Operator**](https://www.geeksforgeeks.org/python-operators/)**s**

Understanding identity [operator](https://www.ionos.com/digitalguide/websites/web-development/python-operators/)s is essential for understanding **object-oriented** programming and [memory management](https://www.geeksforgeeks.org/memory-management-in-python/) since they provide a way to determine if two variables represent the same [memory](https://docs.python.org/3/c-api/memory.html) object.

When comparing two objects' [memory](https://www.javatpoint.com/python-memory-management) locations, identity [operator](https://www.tutorialsteacher.com/python/python-operators)s are utilized

* **Is** [**Operator**](https://www.techbeamers.com/python-operators-tutorial-beginners/)
    
* **Is Not** [**Operator**](https://www.python.org/)
    

### **Is Operator**

*Returns True if two variables reference the same object*

[Python](https://developer.mozilla.org/en-US/docs/Glossary/Python)'s **is-**[**operator**](https://docs.python.org/3/library/operator.html) may be used to determine whether two variables correspond to the same [memory](https://realpython.com/python-memory-management/) item. Instead of determining if the values of the objects are equal, it verifies the identity of each item.

### Example 9: Creating a web application's caching system

To increase speed, you should keep frequently used data in [memory](https://www.honeybadger.io/blog/memory-management-in-python/). You may keep cached data in a dictionary and quickly determine if a given item has already been cached by using the is [operator](https://docs.python.org/3/tutorial/datastructures.html).

```python
# Dictionary to store cached data
cache = {}

def get_data_from_cache(key):
    if key in cache:
        print(f"Getting data for key '{key}' from cache.")
        return cache[key]
    else:
        print(f"Data for key '{key}' not found in cache.")
        return None

# Simulating caching data
data = [1, 2, 3, 4]
cache["my_data"] = data

# Using the get_data_from_cache function
requested_data = get_data_from_cache("my_data")
if requested_data is data:
    print("Using cached data.")
else:
    print("Data not in cache. Fetching from source and caching.")
data.append(5)

requested_data = get_data_from_cache("my_data")
if requested_data is data:
    print("Using cached data.")
else:
    print("Data not in cache. Fetching from source and caching.")
#The is operator returns True if cached data remains unchanged, 
#demonstrating object identity in practical scenarios like caching.
```

The **get\_data\_from\_cache()** function compares the returned data to the cached data using the is [operator](https://www.python.org/downloads/) to verify object identity. If the **is-**[**operator**](https://www.w3schools.com/python/) returns **True**, the modified data is not reflected in the cached data. This demonstrates the **is-**[**operator**](https://docs.python.org/3/tutorial/index.html) usefulness in practical cases like caching.

### Is Not Operator

When determining if two variables relate to separate objects, the is not [operator](https://www.programiz.com/python-programming/online-compiler/) is frequently employed. This might help determine whether things are distinct in [memory](https://realpython.com/python-memory-management/).

### **Example 10**

You use a messaging program and want to know if the recipient of a message has read it. The is not [operator](https://www.tutorialspoint.com/python/index.htm) can be used to detect if a new message object, which denotes that the message has been read, differs from the original message object.

```python
class Message:
    def __init__(self, content, read_status=False):
        self.content = content
        self.read_status = read_status

original_message = Message("Hey there!")


read_message = original_message
read_message.read_status = True

if original_message is not read_message:
    print("The message has been read.")
else:
    print("The message hasn't been read yet.")
```

The **original\_message** and **read\_message** initially reference the same object, but when **read\_status** is updated to **True**, they become different objects with different attributes. The is not operator checks if the objects are different, indicating that the message has been read. This is useful in practical scenarios to track object state changes and determine if two variables reference different objects.

<details data-node-type="hn-details-summary"><summary>Summary</summary><div data-type="detailsContent">In this final installment of our "<a target="_blank" rel="noopener noreferrer nofollow" href="https://www.scientecheasy.com/2022/10/membership-operators-in-python.html/" style="pointer-events: none">Python Operators</a>" series, we explore the world of <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.geeksforgeeks.org/bitwise-hacks-for-competitive-programming/" style="pointer-events: none">bitwise</a>, membership, and identity <a target="_blank" rel="noopener noreferrer nofollow" href="" style="pointer-events: none">operators</a>. These <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.prepbytes.com/blog/python/membership-operator-in-python/" style="pointer-events: none">operators </a>are crucial in handling binary data at the bit level, enabling the manipulation of individual bits within numbers. They are useful in scenarios like data compression, cryptography, and low-level programming. <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.geeksforgeeks.org/python-membership-identity-operators-not-not/" style="pointer-events: none">Membership operators</a> assess the presence or absence of elements in data structures like lists, tuples, and sets, streamlining decision-making processes. They provide a concise and efficient way to determine if a specific item exists within a collection. Lastly, identity <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.w3schools.com/python/gloss_python_membership_operators.asp" style="pointer-events: none">operators </a>discern the identity of objects in <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.educative.io/answers/how-is-memory-managed-in-python" style="pointer-events: none">memory</a>, enabling more informed programming choices and enhancing application efficiency.</div></details>

Thank you for accompanying us on this journey through the diverse landscape of [operators](https://www.analyticsvidhya.com/blog/2021/04/an-overview-of-python-memory-management/) in [Python](https://www.tutorialspoint.com/python/python_operators.htm). Your enthusiasm fuels our commitment to delivering insightful content, and we look forward to embarking on new learning adventures with you.
