Python Reference Library →

Python bytes() Function – Create Immutable Byte Objects

Let’s look at bytes() function – create immutable byte objects

  1. Notice

    bytes() creates an immutable sequence of bytes. Encoding text requires an explicit encoding.

  2. Try

    Follow the example, change its sample, and compare what happens.

  3. Check

    Explain the result and test your understanding.

Watch how it works

Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.

Explore the idea

Follow the code and watch its state change. Guided simulation.

Code
Python
text = 'tea'
data = bytes(text, "utf-8")
print(data)
Live state

Top-level scope

text→Object 1
data→Object 2
Object 1 · str'tea'Object 2 · bytesb'tea'
This step

bytes() creates an immutable sequence of bytes. Encoding text requires an explicit encoding.

Picture bytes() function – create immutable byte objects

bytes() creates an immutable sequence of bytes. Encoding text requires an explicit encoding.

Image brief

Alt text
A diagram for Python bytes() Function – Create Immutable Byte Objects. Instructions: text = 'tea' data = bytes(text, "utf-8") print(data). Displayed result: b'tea'. The final example bindings are text --> object 1 (str); data --> object 2 (bytes). object 1: 'tea'; object 2: b'tea'
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python bytes() Function – Create Immutable Byte Objects". Teaching focus: bytes() creates an immutable sequence of bytes. Encoding text requires an explicit encoding. Depict exactly the relationships and labels in this reference diagram: EXAMPLE INSTRUCTIONS text = 'tea' data = bytes(text, "utf-8") print(data) | v DISPLAYED RESULT b'tea' FINAL BINDINGS text --> object 1 (str) data --> object 2 (bytes) object 1: 'tea' object 2: b'tea' Use a flat vector style, generous spacing, clear arrows and legible labels, with a restrained blue/teal palette on a plain background. The diagram must explain the programming idea accurately. Do not depict variables as boxes containing copied objects when they share a reference. Avoid mascots, decorative screenshots, logos, gradients and extra text. Landscape composition, approximately 3:2, suitable for a course card. Accessible description: A diagram for Python bytes() Function – Create Immutable Byte Objects. Instructions: text = 'tea' data = bytes(text, "utf-8") print(data). Displayed result: b'tea'. The final example bindings are text --> object 1 (str); data --> object 2 (bytes). object 1: 'tea'; object 2: b'tea'

Follow the execution

Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.

Execution workspace

Choose a sample and follow its execution. Guided simulation.

Code
Python
text = 'tea'
data = bytes(text, "utf-8")
print(data)
Live state

Top-level scope

text→Object 1
data→Object 2
Object 1 · str'tea'Object 2 · bytesb'tea'
This step

The example has finished. Compare the final output with the values and references above.

Terminal
Output
b'tea'

What do you expect this program to print?

What does this example display?

text = 'tea'
data = bytes(text, "utf-8")
print(data)
What does this example display?
Choose one answer. You can try again.

Answer and explanation

b'tea'

Follow the printed values in order. The output is: b'tea'

Which explanation matches what you learned?

Which explanation matches what you learned?
Choose one answer. You can try again.

Answer and explanation

bytes() creates an immutable sequence of bytes. Encoding text requires an explicit encoding.

bytes() creates an immutable sequence of bytes. Encoding text requires an explicit encoding.

More examples and reference

Python bytes() Function

The bytes() function in Python is used to create an immutable sequence of bytes. It is commonly used when working with binary data, such as reading from or writing to files, networking, or handling encoded data.

Syntax

bytes([source[, encoding[, errors]]])

Parameters:

  • source (optional) – Data to convert into bytes (e.g., string, iterable, or integer).
  • encoding (optional) – Encoding to use when the source is a string.
  • errors (optional) – Specifies how to handle encoding errors (e.g., 'strict', 'ignore').

Returns:

  • A bytes object, which is an immutable sequence of integers in the range 0 <= x < 256.

Example 1: Creating Empty Bytes

empty = bytes()
print(empty)
b''

Example 2: Convert String to Bytes

text = "hello"
b = bytes(text, encoding="utf-8")
print(b)
b'hello'

Example 3: Create Bytes from List of Integers

data = [65, 66, 67]
b = bytes(data)
print(b)
b'ABC'

Example 4: Using Integer as Argument

b = bytes(4)
print(b)
b'\x00\x00\x00\x00'

This creates a bytes object of size 4 with each byte set to 0.

Use Cases

  • Working with binary files
  • Storing or transmitting encoded data
  • Handling network protocols or buffered data
  • Required when interacting with low-level APIs

Common Mistakes

  • Forgetting to specify encoding when converting a string
  • Providing numbers outside the range 0-255 in a list/iterable
  • Expecting the result to be mutable (use bytearray() for mutable sequences)

Interview Tip

The bytes() function is often useful in interviews involving file I/O, sockets, or data serialization. Remember that it's immutable!

Summary

  • bytes() creates immutable sequences of bytes
  • Can be created from strings (with encoding), integers, or iterables
  • Immutable – to change values, use bytearray()

Practice Problem

Ask the user to input a string, convert it to bytes, and print the result.

user_input = input("Enter a message: ")
b = bytes(user_input, encoding="utf-8")
print("Byte version:", b)

What to remember

Connect what you noticed in the example with the idea below.

Remember

bytes() creates an immutable sequence of bytes. Encoding text requires an explicit encoding.

Watch out for this idea

You can assign a new value to an element of a bytes object.

This is the misconception to avoid.

Reference checks are optional and do not count toward course progress.

    Reference library →