Find the Size of a Tuple in Python
There are several ways to find the “size” of a tuple, depending on whether we are interested in the number of elements or the memory size it occupies. For Example: if we have a tuple like tup = (10, 20, 30, 40, 50)
, calling len(tup)
will return 5
, since there are five elements in the tuple.
Using len()
len() is the easiest way to find the number of elements in a tuple. It returns the count of items stored within the tuple, A quick way to determine the size of a tuple in terms of the number of elements is by using the built-in len()
function.
tup = (0, 1, 2, 'a', 3)
print(len(tup))
Output
5
Explanation: len()
counts how many items are inside the tuple. In the example above, the tuple tup
has 5 elements (0, 1
, 2
, 'a'
, and 3
), so len(tup)
returns 5
.
Table of Content
Using sys.getsizeof()
sys.getsizeof() from the sys
module is used to find the memory size of a tuple (in bytes). It gives us the size of the tuple object itself, including the overhead Python uses for its internal structure.
Note that this does not include the memory used by the elements within the tuple.
import sys
tup = (0, 1, 2, 'a', 3)
print(sys.getsizeof(tup))
Output
80
Explanation: sys.getsizeof(): returns the memory size of the tuple object, which includes the overhead of the tuple structure itself. It does not include the memory size of the individual elements contained within the tuple (for example, the integers or strings themselves).
Note: The size may vary depending on the version of Python and the system architecture.
Using id()
We can use the id()
function to obtain the memory address of the tuple or its elements. This method helps us to understand where objects are stored in memory, but it doesn’t directly give us their size.
tup = (0, 1, 2, 'a', 3)
# Print the memory address of each element
for item in tup:
print(f"Memory address of {item}: {id(item)}")
Output
Memory address of 0: 140202548785072 Memory address of 1: 140202548785104 Memory address of 2: 140202548785136 Memory address of a: 140202548849624 Memory address of 3: 140202548785168
Explanation: The id()
function returns the memory address where the object is stored, which can give insight into how memory is allocated.
Using memoryview()
memoryview() is typically used for low-level memory management and binary data. It creates a view object that provides access to the memory buffer of an object. While not often used for simple tuples, it can be helpful in performance-sensitive scenarios.
tup = (0,1, 2,'a', 3)
memory_view = memoryview(bytearray(str(tup), 'utf-8'))
print(memory_view.nbytes)
Output
17
Explanation: memoryview()
provides a low-level interface to the memory used by an object, often used with binary data.