CodeBlanks Logo Icon CodeBlanks

sys.getsizeof

Learn to measure memory with sys.getsizeof.

What is sys.getsizeof?

sys.getsizeof(obj) returns the number of bytes an object occupies in memory. It is the fundamental tool for memory optimization.

For example sys.getsizeof([1, 2, 3]) gives the size of a list and sys.getsizeof((1, 2, 3)) of a tuple. A list uses more memory than a tuple because it is dynamic. This measurement helps determine which data structure is more efficient. In large datasets small differences can matter.

List vs tuple comparison

A list keeps extra capacity to grow; so it is larger than a tuple with the same items. You see this difference with sys.getsizeof.

For example [1, 2, 3] is about 88 bytes while (1, 2, 3) is 64 bytes. A tuple is immutable, so it needs no extra capacity. This is one reason tuples are preferred for fixed data. getsizeof gives only the container size; it does not count the items inside. For the full size you must measure each item separately.

Practice Compare sizes with getsizeof

Import the module with import sys. Define a = [1, 2, 3] and b = (1, 2, 3). Print sys.getsizeof(a) and sys.getsizeof(b) on separate lines.

Starter code

main.py
# create a list and a tuple
# print their sizes

Sample solution

main.py
import sys

a = [1, 2, 3]
b = (1, 2, 3)
print(sys.getsizeof(a))
print(sys.getsizeof(b))

Expected output

88
64

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match getsizeof concepts

Term Meaning
sys.getsizeof Byte size
list Dynamic container
tuple Immutable container
byte Memory unit

2 Which uses less memory?

main.py
import sys
print(sys.getsizeof([1,2,3]))
print(sys.getsizeof((1,2,3)))
  • Both equal
  • List
  • Tuple Correct answer
  • It depends

Explanation: A tuple is immutable so it keeps no extra capacity; it uses less memory.

3 Complete the getsizeof call

Question
import sys
size = sys.____([1, 2, 3])
Answer
import sys
size = sys.getsizeof([1, 2, 3])

Explanation: sys.getsizeof(obj) returns the byte size.

All lessons in Expert