Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Size of objects in Python

📅 2012-May-10 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ python, size ⬩ 📚 Archive

The getsizeof function from the sys module can be used to obtain the size of objects in Python. Comparing the size of elementary objects in Python with that in other languages can be quite interesting.

# Tried with Python 3.2.2 64-bit
import sys

a = None
sys.getsizeof( a ) # 16

a = 0
sys.getsizeof( a ) # 24

a = 12345678
sys.getsizeof( a ) # 28

a = ""
sys.getsizeof( a ) # 58

a = "hello"
sys.getsizeof( a ) # 68 (2 bytes per letter)

a = []
sys.getsizeof( a ) # 64

a = tuple()
sys.getsizeof( a ) # 48

a = set()
sys.getsizeof( a ) # 224

a = {}
sys.getsizeof( a ) # 272

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧