Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn None and Binary Data | Cross-Type Interactions
Data Types in Python

None and Binary Data

Swipe to show menu

Real programs handle missing values and binary data. Use None to mark "no value", and bytes/bytearray for raw binary content. Know when each is appropriate and how to convert safely between text and bytes.

None for "No Value"

None is a single object meaning "nothing here".

1234567
result = None email = None print(result is None) # True print(email is None) # True if result is None: print("No result yet")

Use is None instead of truthiness checks, since 0 and "" are also falsey.

123
value = 0 print(not value) # True print(value is None) # False

Defaults and Fallbacks

None is used as a clear marker that a value is intentionally missing. It lets you distinguish between "no value provided" and valid values like 0 or "", making defaults and fallbacks safer and more predictable.

1234567
x = None print(x or "unknown") # 'unknown' print("unknown" if x is None else x) x = 0 print(x or "unknown") # 'unknown' print("unknown" if x is None else x) # 0

Functions and Parameters

This example shows how a function uses a parameter set to None as a signal that no tag was provided. It allows the function to assign a safe default while still letting the caller override it when needed.

1234567
def add_tag(text, tag=None): if tag is None: tag = "general" return f"[{tag}] {text}" print(add_tag("hello")) # [general] hello print(add_tag("hello", "news")) # [news] hello

Binary Data

str holds text, bytes and bytearray hold raw byte values.

1234
b1 = b"hello" b2 = bytes([72, 105]) buf = bytearray(b"abc") buf[0] = 65

Encoding and Decoding

Encoding converts text into bytes so it can be stored or transferred reliably, while decoding restores those bytes back into readable text. Using a defined encoding like UTF-8 ensures characters are preserved correctly.

123
text = "café" data = text.encode("utf-8") back = data.decode("utf-8")

Binary Data in Practice

Use bytes and bytearray for handling raw binary information. These types are essential for tasks where data is not just text, such as:

  • Reading and writing files in binary mode (like images, audio, or executable files);
  • Sending and receiving data over networks, where you must transmit precise byte sequences;
  • Parsing or constructing binary protocols, for example, when communicating with hardware or low-level APIs.

bytes vs bytearray

  • bytes objects are immutable: you cannot change their contents after creation. Use them when you need fixed binary data, such as file contents or cryptographic hashes;
  • bytearray objects are mutable: you can modify their contents in place. This is useful for building or editing binary data before saving or sending it.

Example: Modifying Binary Data

# Create a bytes object (immutable)
data = b"hello"
# Create a mutable copy
data_mutable = bytearray(data)
data_mutable[0] = 72  # Change 'h' (104) to 'H' (72)
print(data_mutable)  # bytearray(b'Hello')

Converting Between bytes and bytearray

  • Convert bytes to bytearray to allow modifications:
    b = b"data"
    ba = bytearray(b)
    
  • Convert bytearray back to bytes for storage or transmission:
    ba = bytearray(b"abc")
    b = bytes(ba)
    

Encoding and Decoding

  • Use .encode() on a string to get a bytes object with a specific encoding (like UTF-8);
  • Use .decode() on a bytes or bytearray object to get a string.

This is crucial when working with file I/O or network data, where you often receive or send raw bytes and need to convert them to or from readable text.

Typical Use Cases

  • File I/O:
    • Open files in binary mode ("rb" or "wb") to read or write exact bytes.
  • Network Data:
    • Socket communication sends and receives data as bytes.
  • Binary Protocols:
    • Construct or parse packets using bytearray for efficient in-place edits.

Understanding when to use each type helps you write robust code for real-world data handling.

Typical Use Cases for Bytes and Bytearray

You use bytes and bytearray when working directly with raw binary data, rather than text. These types are essential in several scenarios:

  • Reading or writing binary files, such as images, audio, or executables;
  • Handling network data, since sockets send and receive bytes, not strings;
  • Interacting with binary protocols, where you must construct or parse messages as sequences of bytes.

bytes is an immutable sequence, meaning you cannot change its contents after creation. This is ideal when you need to ensure the data stays unchanged, such as when reading a file or receiving a network packet.

bytearray is mutable, so you can modify its contents in place. Use bytearray when you need to build up a message, alter parts of a buffer, or efficiently manipulate binary data before sending or saving it.

When to use each:

  • Use bytes for fixed, read-only binary data, like file contents or network messages you do not need to change;
  • Use bytearray when you need to edit, append, or otherwise modify the binary data before further processing or transmission.

Converting Between bytes and bytearray

You can convert between bytes (immutable) and bytearray (mutable) objects easily in Python. This lets you choose the right type for your needs—bytes for fixed data, bytearray when you need to modify the content.

  • Use the bytes() constructor to turn a bytearray into an immutable bytes object;
  • Use the bytearray() constructor to make a mutable copy from a bytes object.

This is useful when you need to edit binary data (using bytearray), then lock it down (using bytes) for safe storage or transmission.

raw = bytearray(b"data")
raw[0] = 68  # Change first byte to 'D'
locked = bytes(raw)  # Convert to immutable bytes

b = b"example"
mutable = bytearray(b)  # Convert to mutable bytearray
mutable.append(33)      # Add '!' (ASCII 33)

Once converted to bytes, you cannot change the content. Use bytearray when you need to edit binary data before finalizing it as bytes.

1234567891011
# Convert bytes to bytearray b = b"hello" ba = bytearray(b) # Modify the bytearray (change 'h' to 'H') ba[0] = ord('H') print(ba) # bytearray(b'Hello') # Convert bytearray back to bytes b2 = bytes(ba) print(b2) # b'Hello'
123456
try: b"ID:" + "123" except TypeError as e: print(e) ok = b"ID:" + "123".encode("utf-8")

Length Differences

Some characters take one text element but multiple bytes, so their length in str and in encoded form can differ. This happens because encodings like UTF-8 may use more than one byte to represent a single character.

123
ch = "é" len(ch) # 1 len(ch.encode()) # 2

Files

Binary files must be opened in "rb" mode so their raw bytes are read exactly as stored. This prevents Python from trying to interpret the data as text.

# with open("example.png", "rb") as f:
#     blob = f.read()
question mark

Which check correctly detects a missing value?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 3

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

None and Binary Data

Real programs handle missing values and binary data. Use None to mark "no value", and bytes/bytearray for raw binary content. Know when each is appropriate and how to convert safely between text and bytes.

None for "No Value"

None is a single object meaning "nothing here".

1234567
result = None email = None print(result is None) # True print(email is None) # True if result is None: print("No result yet")

Use is None instead of truthiness checks, since 0 and "" are also falsey.

123
value = 0 print(not value) # True print(value is None) # False

Defaults and Fallbacks

None is used as a clear marker that a value is intentionally missing. It lets you distinguish between "no value provided" and valid values like 0 or "", making defaults and fallbacks safer and more predictable.

1234567
x = None print(x or "unknown") # 'unknown' print("unknown" if x is None else x) x = 0 print(x or "unknown") # 'unknown' print("unknown" if x is None else x) # 0

Functions and Parameters

This example shows how a function uses a parameter set to None as a signal that no tag was provided. It allows the function to assign a safe default while still letting the caller override it when needed.

1234567
def add_tag(text, tag=None): if tag is None: tag = "general" return f"[{tag}] {text}" print(add_tag("hello")) # [general] hello print(add_tag("hello", "news")) # [news] hello

Binary Data

str holds text, bytes and bytearray hold raw byte values.

1234
b1 = b"hello" b2 = bytes([72, 105]) buf = bytearray(b"abc") buf[0] = 65

Encoding and Decoding

Encoding converts text into bytes so it can be stored or transferred reliably, while decoding restores those bytes back into readable text. Using a defined encoding like UTF-8 ensures characters are preserved correctly.

123
text = "café" data = text.encode("utf-8") back = data.decode("utf-8")

Binary Data in Practice

Use bytes and bytearray for handling raw binary information. These types are essential for tasks where data is not just text, such as:

  • Reading and writing files in binary mode (like images, audio, or executable files);
  • Sending and receiving data over networks, where you must transmit precise byte sequences;
  • Parsing or constructing binary protocols, for example, when communicating with hardware or low-level APIs.

bytes vs bytearray

  • bytes objects are immutable: you cannot change their contents after creation. Use them when you need fixed binary data, such as file contents or cryptographic hashes;
  • bytearray objects are mutable: you can modify their contents in place. This is useful for building or editing binary data before saving or sending it.

Example: Modifying Binary Data

# Create a bytes object (immutable)
data = b"hello"
# Create a mutable copy
data_mutable = bytearray(data)
data_mutable[0] = 72  # Change 'h' (104) to 'H' (72)
print(data_mutable)  # bytearray(b'Hello')

Converting Between bytes and bytearray

  • Convert bytes to bytearray to allow modifications:
    b = b"data"
    ba = bytearray(b)
    
  • Convert bytearray back to bytes for storage or transmission:
    ba = bytearray(b"abc")
    b = bytes(ba)
    

Encoding and Decoding

  • Use .encode() on a string to get a bytes object with a specific encoding (like UTF-8);
  • Use .decode() on a bytes or bytearray object to get a string.

This is crucial when working with file I/O or network data, where you often receive or send raw bytes and need to convert them to or from readable text.

Typical Use Cases

  • File I/O:
    • Open files in binary mode ("rb" or "wb") to read or write exact bytes.
  • Network Data:
    • Socket communication sends and receives data as bytes.
  • Binary Protocols:
    • Construct or parse packets using bytearray for efficient in-place edits.

Understanding when to use each type helps you write robust code for real-world data handling.

Typical Use Cases for Bytes and Bytearray

You use bytes and bytearray when working directly with raw binary data, rather than text. These types are essential in several scenarios:

  • Reading or writing binary files, such as images, audio, or executables;
  • Handling network data, since sockets send and receive bytes, not strings;
  • Interacting with binary protocols, where you must construct or parse messages as sequences of bytes.

bytes is an immutable sequence, meaning you cannot change its contents after creation. This is ideal when you need to ensure the data stays unchanged, such as when reading a file or receiving a network packet.

bytearray is mutable, so you can modify its contents in place. Use bytearray when you need to build up a message, alter parts of a buffer, or efficiently manipulate binary data before sending or saving it.

When to use each:

  • Use bytes for fixed, read-only binary data, like file contents or network messages you do not need to change;
  • Use bytearray when you need to edit, append, or otherwise modify the binary data before further processing or transmission.

Converting Between bytes and bytearray

You can convert between bytes (immutable) and bytearray (mutable) objects easily in Python. This lets you choose the right type for your needs—bytes for fixed data, bytearray when you need to modify the content.

  • Use the bytes() constructor to turn a bytearray into an immutable bytes object;
  • Use the bytearray() constructor to make a mutable copy from a bytes object.

This is useful when you need to edit binary data (using bytearray), then lock it down (using bytes) for safe storage or transmission.

raw = bytearray(b"data")
raw[0] = 68  # Change first byte to 'D'
locked = bytes(raw)  # Convert to immutable bytes

b = b"example"
mutable = bytearray(b)  # Convert to mutable bytearray
mutable.append(33)      # Add '!' (ASCII 33)

Once converted to bytes, you cannot change the content. Use bytearray when you need to edit binary data before finalizing it as bytes.

1234567891011
# Convert bytes to bytearray b = b"hello" ba = bytearray(b) # Modify the bytearray (change 'h' to 'H') ba[0] = ord('H') print(ba) # bytearray(b'Hello') # Convert bytearray back to bytes b2 = bytes(ba) print(b2) # b'Hello'
123456
try: b"ID:" + "123" except TypeError as e: print(e) ok = b"ID:" + "123".encode("utf-8")

Length Differences

Some characters take one text element but multiple bytes, so their length in str and in encoded form can differ. This happens because encodings like UTF-8 may use more than one byte to represent a single character.

123
ch = "é" len(ch) # 1 len(ch.encode()) # 2

Files

Binary files must be opened in "rb" mode so their raw bytes are read exactly as stored. This prevents Python from trying to interpret the data as text.

# with open("example.png", "rb") as f:
#     blob = f.read()
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 3
some-alt