Monday, January 13, 2025
HomeProgrammingHow do I determine the size of an object in Python?

How do I determine the size of an object in Python?

To determine the size of an object in Python, use sys.getsizeof() from the sys module. It measures the memory (in bytes) used by the object itself. For example:

import sys

data = [1, 2, 3]
print(sys.getsizeof(data)) # Outputs the size of the list

See also  System Calls in Operating System (OS)

However, sys.getsizeof() doesn’t include memory used by elements inside collections (e.g., lists or dictionaries). For a complete size, use pympler:

from pympler import asizeof

data = [1, 2, [3, 4]]
print(asizeof.asizeof(data)) # Total memory usage

This helps optimize memory in programs by analyzing object sizes.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x