Find the size of a Set in Python
Last Updated :
10 Sep, 2025
A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements. Python’s set class represents the mathematical notion of a set. The size of a set here refers to the memory occupied (in bytes), not the number of elements. We’ll explore different ways to measure it.
Using getsizeof() function
The getsizeof() function from Python’s sys module returns the memory used by an object, including garbage collection overhead. It has been implemented in the below example.
Example: We import sys module, create three different sets and then pass each set into sys.getsizeof() to check its memory usage.
Python
import sys
# sample Sets
Set1 = {"A", 1, "B", 2, "C", 3}
Set2 = {"Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu"}
Set3 = {(1, "Lion"), (2, "Tiger"), (3, "Fox")}
# print the sizes of sample Sets
print("Size of Set1:", sys.getsizeof(Set1), "bytes")
print("Size of Set2:", sys.getsizeof(Set2), "bytes")
print("Size of Set3:", sys.getsizeof(Set3), "bytes")
OutputSize of Set1: 472 bytes
Size of Set2: 472 bytes
Size of Set3: 216 bytes
Explanation:
- sys.getsizeof(Set1): Calculates memory of Set1 including Python object overhead.
- The result includes garbage collection overhead, which is why values may look larger than expected
- This method gives total memory usage of the set object in memory.
Using inbuilt sizeof() method
Python also has an inbuilt __sizeof__() method to determine the space allocation of an object without any additional garbage value. It has been implemented in the below example.
Example: We call the built-in __sizeof__() method directly on each set object to get its memory usage.
Python
import sys
# sample Sets
Set1 = {"A", 1, "B", 2, "C", 3}
Set2 = {"Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu"}
Set3 = {(1, "Lion"), (2, "Tiger"), (3, "Fox")}
# print the sizes of sample Sets
print("Size of Set1:", Set1.__sizeof__(), "bytes")
print("Size of Set2:", Set2.__sizeof__(), "bytes")
print("Size of Set3:", Set3.__sizeof__(), "bytes")
OutputSize of Set1: 456 bytes
Size of Set2: 456 bytes
Size of Set3: 200 bytes
Explanation:
- Set1.__sizeof__(): Returns memory taken only by the set data structure itself.
- Unlike getsizeof(), it excludes garbage collection overhead.
- This gives a slightly smaller value compared to sys.getsizeof().
Note: sys.getsizeof() includes Python’s garbage collection overhead, so values are usually slightly higher than __sizeof__().
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice