Get the length of a Bytes object in Python

avatar

Borislav Hadzhiev

Tue Jun 14 20221 min read

Get the length of a Bytes object in Python #

Use the len() function to get the length of a bytes object, e.g. len(my_bytes). The len() function returns the length (the number of items) of an object and can be passed a sequence (a bytes, string, list, tuple or range) or a collection (a dictionary, set, or frozen set).

main.py
my_bytes = 'hello'.encode('utf-8') print(type(my_bytes)) # 👉️ <class 'bytes'> print(len(my_bytes)) # 👉️ 5

The len() function returns the length (the number of items) of an object.

The example shows how to get the number of bytes in the bytes object.

Here is another example with some special characters.

main.py
my_bytes = 'éé'.encode('utf-8') print(type(my_bytes)) # 👉️ <class 'bytes'> print(len(my_bytes)) # 👉️ 4

If you need to get the size of an object, use the sys.getsizeof() method.

main.py
import sys my_bytes = 'hello'.encode('utf-8') print(sys.getsizeof(my_bytes)) # 👉️ 38 print(sys.getsizeof('hello')) # 👉️ 54

The sys.getsizeof method returns the size of an object in bytes.

The object can be any type of object and all built-in objects return correct results.

The size of an object includes the data stored by the object, the attributes, the methods, etc.

The getsizeof method only accounts for the direct memory consumption of the object, not the memory consumption of objects it refers to.

The getsizeof() method calls the __sizeof__ method of the object, so it doesn't handle custom objects that don't implement it.

Use the search field on my Home Page to filter through my more than 1,000 articles.