Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
No results
  • About AskPython
  • Blog
  • Contact Me
  • Free Online Developer Tools Hub
  • Home
  • Meet the Team
  • Privacy Policy
  • Python
  • Python Course for Beginners Online FREE
  • Python Tutorial – Mega Index
  • Terms and Conditions

🚀 Supercharge your YouTube channel's growth with AI.

Try YTGrowAI Free
  • Home
  • Blog
  • About AskPython
  • Python Course
  • Start Here

Python bytes()

  • Vijaykrishna RamVijaykrishna Ram
  • January 19, 2020
  • Built-in Methods
Python bytes()

Python bytes() is a built-in function which returns a bytes object that is an immutable sequence of integers in the range 0 <= x < 256. Depending on the type of object passed as the source, it initializes the byte object accordingly.

Let’s look at how we can use this function in this article.


Syntax

This takes in three optional parameters, namely the:

  • source -> The source which initializes the byte array
  • encoding -> The encoding of the source string (can be UTF-8, etc).
  • errors -> The behavior of the function when encoding the source string fails.
byte_array = bytes(source, encoding, errors)

Since all three arguments are optional, we can pass an empty string to generate an empty byte array (Byte array of size 0).

Depending on the type of the source parameter, an appropriate byte array will be initialized.

  • If source is a String, Python bytes() will convert the string to bytes using str.encode(). Therefore, we must also provide the encoding and optionally errors, as encode() is being used to process the string.
  • If source is an Integer, Python bytes() will creates an array of provided integer size, all initialized to NULL.
  • If source is of class Object, a read-only buffer of the object will be used to initialize the byte array.
  • If source is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

If source is None, this will give a TypeError, as it cannot convert a None object to a byte array.

To understand the function better, let’s look at some examples.


Using Python bytes()

With no and None arguments

b = bytes()
print(b)
c = bytes(None)
print(c)

Output

b''
TypeError: cannot convert 'NoneType' object to bytes

With a source String

Any string provided without the encoding will raise a TypeError.

Similarly, trying to modify the bytes object will also give the same exception, since it is immutable by nature.

try:
    a = bytes('Hello from AskPython')
except TypeError:
    print('We need to specify string encoding always!')

b = bytes('Hello from AskPython', 'UTF-8')
print(type(b), b)

try:
    b[0] = 10
except TypeError:
    print('byte objects are immutable!')

Output

We need to specify string encoding always!
<class 'bytes'> b'Hello from AskPython'
byte objects are immutable!

With a source Integer

An integer zero-initializes that many byte element objects in the array.

a = bytes(10)
print(type(a), a)

Output

<class 'bytes'> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

As you can see, the bytes object is a Zero initialized array consisting of 10 elements.

With a source iterable

This initializes the array with len(iterable) number of elements, each having a value equal to the corresponding element on the iterable.

Byte array values can be accessed through normal iteration, but cannot be modified since they are immutable.

a = bytes([1, 2, 3])
print(type(a), a)
print('Length =', len(a))

# To access the byte array values, we can iterate through it!
for byte_obj in a:
    print(byte_object)

Output

<class 'bytes'> b'\x01\x02\x03'
Length = 3
1
2
3

Anything else on the iterable will result in a TypeError

>>> a = bytes([1, 2, 3, 'Hi'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer

Conclusion

In this article, we learned about Python bytes() function, which can convert suitable objects to a byte array.


References

  • JournalDev article on bytes()

Vijaykrishna Ram
Vijaykrishna Ram
Articles: 99
Python Set Union
Previous Post Python Set Union
Next Post Python chr() and ord()
Python chr() and ord()

Related Posts

Print Function Python: Arguments and Output

Print Function Python: Arguments and Output

  • November 28, 2026
How to Use Input Function in Python

How to Use Input Function in Python

  • November 28, 2026
How to Open Files in Python

How to Open Files in Python

  • November 23, 2026

Partner Websites

  • GoLangDocs
  • LinuxForDevices
  • CodeForGeek

Popular Categories

  • Python Programming
  • Python Modules
  • OOPS in Python
  • Python Programming Examples
  • Strings in Python

Hall of Fame

  • Python Programming
  • OOPS in Python
  • Creating Python Modules
  • Args and Kwargs in Python
  • Python Dictionary (Dict) Tutorial
  • Python List – 15 Things You MUST Know
  • Python Set – Things You MUST Know
  • Python String Functions: Methods by Task

Important Links

  • Home
  • Python Course
  • Start Here
  • Blog
  • About AskPython
Latest posts
  • np.linalg.eig: Eigenvalues and Eigenvectors
  • What Does %s Mean in a Python Format String?
  • How to Use np.sin() in NumPy
  • cv2.imread: Load Images with OpenCV
  • pd.read_json: Read JSON Into a DataFrame

Copyright © 2026 - AskPython. All rights reserved.