TechBeamersTechBeamers
  • Viral Tips 🔥
  • Free CoursesTOP
  • TutorialsNEW
    • Python Tutorial
    • Python Examples
    • C Programming
    • Java Programming
    • MySQL Tutorial
    • Selenium Tutorial
    • Selenium Python
    • Playwright Python
    • Software Testing Tutorial
    • Agile Concepts
    • Linux Concepts
    • HowTo Guides
    • Android Topics
    • AngularJS Guides
    • Learn Automation
    • Technology Guides
  • Top Interviews & Quizzes
    • SQL Interview Questions
    • Testing Interview Questions
    • Python Interview Questions
    • Selenium Interview Questions
    • C Sharp Interview Questions
    • Java Interview Questions
    • Web Development Questions
    • PHP Interview Questions
    • Python Quizzes
    • Java Quizzes
    • Selenium Quizzes
    • Testing Quizzes
    • HTML CSS Quiz
    • Shell Script Quizzes
  • ToolsHOT
    • Python Online Compiler
    • Python Code Checker
    • C Online Compiler
    • Review Best IDEs
    • Random Letter Gen
    • Random Num Gen
TechBeamersTechBeamers
Search
  • Viral Tips 🔥
  • Free CoursesTOP
  • TutorialsNEW
    • Python Tutorial
    • Python Examples
    • C Programming
    • Java Programming
    • MySQL Tutorial
    • Selenium Tutorial
    • Selenium Python
    • Playwright Python
    • Software Testing Tutorial
    • Agile Concepts
    • Linux Concepts
    • HowTo Guides
    • Android Topics
    • AngularJS Guides
    • Learn Automation
    • Technology Guides
  • Top Interviews & Quizzes
    • SQL Interview Questions
    • Testing Interview Questions
    • Python Interview Questions
    • Selenium Interview Questions
    • C Sharp Interview Questions
    • Java Interview Questions
    • Web Development Questions
    • PHP Interview Questions
    • Python Quizzes
    • Java Quizzes
    • Selenium Quizzes
    • Testing Quizzes
    • HTML CSS Quiz
    • Shell Script Quizzes
  • ToolsHOT
    • Python Online Compiler
    • Python Code Checker
    • C Online Compiler
    • Review Best IDEs
    • Random Letter Gen
    • Random Num Gen
Follow US
© TechBeamers. All Rights Reserved.
Python Basic

Python XOR Operator (^) Explained with Simple Examples for Beginners

Last updated: May 12, 2025 11:55 pm
Harsh S.
By
Harsh S.
Harsh S. Avatar
ByHarsh S.
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale...
Follow:
No Comments
1 week ago
Share
16 Min Read
SHARE

The Python XOR (^) operator is explained with clear examples. Understand bitwise logic easily and learn how to apply XOR in real Python code.

Contents
Understand the Python XOR OperatorWhat is XOR in Python?How XOR Works in Python?How is XOR different from OR and AND?XOR Examples in PythonExample:1 XOR Boolean Values in PythonExample:2 XOR with Strings in PythonExmaple:4 Apply XOR on ListsExmaple:4 Apply XOR on BytesApplications of XOR in PythonData EncryptionChecksum GenerationToggling BitsUsing XOR for Swapping VariablesXOR as a Hash FunctionGenerating Gray CodeBitwise XOR vs. Logical XORFrequently Asked Questions about Python XOR OperatorYour Thoughts? How Was Your Experience with XOR in Python?

Understand the Python XOR Operator

XOR operator has a special place in Python. It has several real-time applications like cryptography, bit manipulation, generating checksums, etc. Firstly, let’s understand what it is and how to use it in Python. Later, this tutorial will present examples to help you grasp its usage in Python.

What is XOR in Python?

The XOR operator, denoted by the caret symbol (^), is one of the bitwise operators in Python used for the exclusive OR (XOR) operation. XOR is a logical operation that compares two binary values and returns a new one. The XOR operator plays a crucial role in various programming tasks due to its unique functions.

How XOR Works in Python?

The XOR operator works by checking the respective bit of the two integer numbers and produces 1 if the bits are different, otherwise, it returns 0.

You might find this helpful: How to check if an integer is in range.

To better understand how XOR works, let’s consider two variables, A and B. Both of them store an integer number in binary format.

A = 1100
B = 1010

The XOR operation (A ^ B) compares each pair of bits in A and B:

    A: 1 1 0 0
    B: 1 0 1 0
       --------
A ^ B: 0 1 1 0

The result is 0110, which is the XOR of A and B. To help you easily grasp the concept, here is a simple visual example.

      A           B        Result (A ^ B)
    +---+       +---+       +---+
    | 1 | XOR   | 1 | --->  | 0 |
    +---+       +---+       +---+
    | 1 | XOR   | 0 | --->  | 1 |
    +---+       +---+       +---+
    | 0 | XOR   | 1 | --->  | 1 |
    +---+       +---+       +---+
    | 0 | XOR   | 0 | --->  | 0 |
    +---+       +---+       +---+

Let’s also illustrate the XOR operation with Python code:

# XOR operation in Python
A = 10  # binary 1010
B = 6   # binary 0110
result = A ^ B
print(result)  # Output: 12 (binary 1100)

By using the Caret “^”

Python uses the caret sign “^” for performing the XOR operation. Below is its syntax.

Basic XOR Syntax

XORresult = operand1 ^ operand2

It takes two integer operands, XOR their binary value bit by bit, and returns the result. See the following example.

# Using XOR with ^
x = 25  # binary 11001
y = 18  # binary 10010
result = x ^ y
print(result)  # Output: 11 (binary 01011)

By using the XOR() Function

Python provides a dedicated function operator.xor() in the operator module for performing the XOR operation. It is slightly a better alternative to the ^ sign in terms of readability.

# Using XOR with operator.xor()
import operator
x = 15  # binary 1111
y = 9   # binary 1001
result = operator.xor(x, y)
print(result)  # Output: 6 (binary 0110)

Apart from the integer numbers, xor can also be applied to different data types in Python such as strings and bytes.

How is XOR different from OR and AND?

The XOR, OR, and AND, all of these are bitwise operators in Python. Let’s understand how these operations are different from each other.

  • The XOR operator returns 1 only if the corresponding bits of the operands are different. It returns 0 (False) if both bits are equal. It does not matter whether they both are 0 or 1.
  • Next, the AND operator will return 1 only if both corresponding bits are 1. If any of the bits is zero, it will always return false.
  • Subsequently, the OR operator requires at least one bit to be 1, then it will pass. It returns 0 (False) only if both bits are 0.

XOR Examples in Python

Let’s take a few examples to clarify the use of the XOR operator.

Example:1 XOR Boolean Values in Python

We’ll use two boolean variables and apply the XOR operation in four combinations.

a = True
b = True
result1 = a ^ b  # False

a = True
b = False
result2 = a ^ b  # True

a = False
b = True
result3 = a ^ b  # True

a = False
b = False
result4 = a ^ b  # False

print("Result 1:", result1)  # False
print("Result 2:", result2)  # True
print("Result 3:", result3)  # True
print("Result 4:", result4)  # False

In Python, for arithmetic calculations, the value “True” represents 1, and “False” means 0. So, even though variables a and b are boolean, XOR operates on them like bits and returns the bitwise XOR result.

Example:2 XOR with Strings in Python

When working with strings in Python, you might need to apply bitwise operations like XOR. XOR with strings compares the characters of two strings and returns a new string with the corresponding characters XORed together.

Let’s take an example. Suppose we have two strings, “Hello” and “World”. We apply XOR on their characters as follows:

'H' XOR 'W' = '\x0f'
'e' XOR 'o' = '\x1c'
'l' XOR 'r' = '\x1b'
'l' XOR 'l' = '\x1a'
'o' XOR 'd' = '\x1d'

The resulting XORed string is '\x0f\x1c\x1b\x1a\x1d'. Below is the code using Python XOR with strings.

# XOR with Strings
def xor_strings(str1, str2):
    result = ""
    for c1, c2 in zip(str1, str2):
        result += chr(ord(c1) ^ ord(c2))
    return result

# Example:
text1 = "Hello"
text2 = "World"
xor_result = xor_strings(text1, text2)
print(xor_result)  # Output: '\x0f\x1c\x1b\x1a\x1d'

Exmaple:4 Apply XOR on Lists

For this example, we are using two lists containing boolean values.

# Xor the lists
ls1 = [True, False, True]
ls2 = [True, True, False]

xor_result = [x ^ y for x, y in zip(ls1, ls2)]
print("Result:", xor_result)  # Output: [False, True, True]

We have to perform the XOR operation on the corresponding elements of two lists. Hence, we used list comprehension to iterate and the zip function to pair up the adjacent elements. The result of the xor operations was stored in a list as well.

Exmaple:4 Apply XOR on Bytes

XOR is easy to use with bytes in Python. It directly compares each bit of the two objects and returns a new byte with the corresponding bits XORed together.

Let’s understand it with an example. Suppose we have two objects of byte type, b'\x10\x20\x30\x40' and b'\x05\x15\x25\x35'. We apply XOR on their bytes as follows:

0x10 XOR 0x05 = 0x15
0x20 XOR 0x15 = 0x35
0x30 XOR 0x25 = 0x15
0x40 XOR 0x35 = 0x75

The resulting XORed bytes object is b'\x15\x35\x15\x75'. The code for the above example is as follows.

# XOR with Bytes
def xor_bytes(bytes1, bytes2):
    return bytes(x ^ y for x, y in zip(bytes1, bytes2))

# Example:
data1 = b'\x10\x20\x30\x40'
data2 = b'\x05\x15\x25\x35'
xor_result = xor_bytes(data1, data2)
print(xor_result)  # Output: b'\x15\x35\x15\x75'

Applications of XOR in Python

The XOR operator has a variety of applications in Python. Some of the most common applications include:

Data Encryption

XOR is widely used for data encryption. It is a simple and effective encryption method that is relatively easy to implement. XOR encryption works by XORing the data with a secret key.

This means each bit in the data is XORed with the corresponding bit in the key. The result of this XOR operation is a new piece of data that is encrypted. To decrypt the data, the same key is used to XOR the encrypted data. This will result in the original piece of data.

# Data Encryption using XOR
def encrypt_decrypt(data, key):
    return ''.join(chr(ord(d) ^ key) for d in data)

message = "Hello, XOR!"
key = 42
encrypted_message = encrypt_decrypt(message, key)
decrypted_message = encrypt_decrypt(encrypted_message, key)
print(encrypted_message)  # Output: "\x07\x1c\x15\x15\x1f\x1f\x12\x1b\x15\x14"
print(decrypted_message)  # Output: "Hello, XOR!"

Checksum Generation

XOR operator can also be used to produce checksums. It helps in catching errors during network data transfer. In this process, each byte of data is XORed with the previous byte, and the final result is the checksum. Refer to the following Python code:

# Checksum Generation using XOR
def generate_checksum(data):
    checksum = 0
    for byte in data:
        checksum ^= byte
    return checksum

data_to_transmit = [0x54, 0x21, 0x87, 0x3F]
checksum = generate_checksum(data_to_transmit)
print(hex(checksum))  # Output: 0xB7

Toggling Bits

XOR is also useful for toggling individual bits in binary numbers, which finds applications in various programming chores. For example, you can toggle a specific bit to 0 or 1 using XOR with an appropriate bitmask.

# Toggling bits using XOR
number = 15  # binary 1111
toggle_mask = 8  # binary 1000 (toggling the 4th bit)
result = number ^ toggle_mask
print(result)  # Output: 7 (binary 0111)

Using XOR for Swapping Variables

One of the fascinating applications of XOR is swapping the values of two variables without using a third variable. This bitwise operation works because XORing a number with itself results in 0.

# Swapping variables using XOR
x = 10
y = 20
x ^= y
y ^= x
x ^= y
print(x)  # Output: 20
print(y)  # Output: 10

XOR as a Hash Function

Another interesting usage of XOR is to use it for hashing. However, it is not always suitable for cryptographic purposes due to its simple nature.

# Simple XOR-based hash function
def simple_hash(data):
    hash_value = 0
    for byte in data:
        hash_value ^= byte
    return hash_value

data_to_hash = b"Hello, XOR!"
hashed_value = simple_hash(data_to_hash)
print(hashed_value)  # Output: 108

Generating Gray Code

XOR plays a significant role in generating Gray Code, a binary numeral system where two successive values differ in only one-bit position. It is widely used in digital communications and error-correcting codes.

# Generating Gray Code using XOR
def generate_gray_code(n):
    return n ^ (n >> 1)

for i in range(16):
    print(generate_gray_code(i))

# Output:
# 0 1 3 2 6 7 5 4 12 13 15 14 10 11 9 8

Undoubtedly, the above examples demonstrate numerous applications of XOR in Python. However, there shall be more areas that are beyond the scope of this article. Lastly, it’s essential to explain the distinction between the bitwise XOR and the logical XOR.

Bitwise XOR vs. Logical XOR

It’s important to note the difference between bitwise XOR and logical XOR in Python. While bitwise XOR operates at the bit level, logical XOR operates on Boolean values, returning True if the operands are different and False if they are the same.

# Bitwise XOR vs. Logical XOR
a = True
b = False
bitwise_result = a ^ b
logical_result = a != b
print(bitwise_result)  # Output: True
print(logical_result)  # Output: True

XOR is a bitwise operator that is essential in Boolean algebra. In binary arithmetic, it behaves as an addition without carry. It is also extensively used in network security protocols, such as IPsec and SSL/TLS. The purpose of XOR in these protocols is to combine cryptographic keys and ensure the confidentiality and authenticity of data during transmission.

Frequently Asked Questions about Python XOR Operator

What is the XOR operator in Python?

The XOR operator (^) compares bits and returns 1 when they are different, and 0 when they are the same. It’s used for bitwise operations.

How does XOR work with integers?

XOR compares each bit of two integers. For each position, if the bits differ, it sets the bit to 1; otherwise, it sets it to 0.

What is a practical use of XOR in Python?

It’s useful in toggling flags, basic encryption, or finding a unique number in a list where every other number appears twice.

Can XOR be used with booleans?

Yes, you can use XOR with True and False. True ^ False gives True, but True ^ True and False ^ False give False.

Is XOR (^) the same as !=?

No. While they can give the same result with booleans, ^ is a bitwise operator, and != is a logical comparison operator.

Your Thoughts? How Was Your Experience with XOR in Python?

Congratulations! 🎉 You’ve completed the Python XOR tutorial and now have a solid understanding of the XOR operator and its applications. With this knowledge, you can confidently use XOR in your own Python code.

We’d love to hear from you! 💬 How did you find this tutorial? Was it helpful? Do you have any questions or interesting use cases for XOR? Drop your thoughts in the comments below! 🚀

Also, if you enjoyed this tutorial, support us by subscribing to our YouTube channel 📺—where we share more Python tips, tutorials, and coding insights. Stay connected and keep learning! 🔥

Related

Share This Article
Flipboard Copy Link
Subscribe
Notify of
guest

guest

0 Comments
Newest
Oldest
Inline Feedbacks
View all comments

List of Topics

Stay Connected

FacebookLike
XFollow
YoutubeSubscribe
LinkedInFollow

Subscribe to Blog via Email

Enter your email address to subscribe to latest knowledge sharing updates.

Join 1,011 other subscribers

Continue Reading

  • Python Float NumbersSep 28
  • Python Check Variable TypeOct 28
  • Python Nested ListOct 29
  • Python Multiline CommentsNov 6
  • Python Check VersionNov 21
  • Python Exception HandlingAug 13
  • Python: 30 Programming Tips & TricksSep 18
  • Python Try-ExceptJun 16
  • Python Keywords, Identifiers, & VariablesJul 15
  • Python Statement & IndentationOct 30
View all →

RELATED TUTORIALS

Python Data Types - Learn from Basic to Advanced

Understand Data Types in Python

By Meenakshi Agarwal
1 month ago
python add two list elements- 4 ways

How to Add Elements of Two Lists

By Meenakshi Agarwal
1 month ago
Python List Concepts Explained with Examples

Python List

By Meenakshi Agarwal
1 month ago
Define Python String Replace Method with Examples

Python String Replace()

By Meenakshi Agarwal
1 month ago
© TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
wpDiscuz