Borislav Hadzhiev
Tue Jun 14 2022·1 min read
Photo by Jordan Donaldson
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).
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.
Here is another example with some special characters.
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.
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 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.