Could you rent a tuple?

Pradeep Varanasi
4 min readAug 9, 2022

--

Traversing through the memory blocks of a tuple

Photo by Victor on Unsplash

Introduction:

The most commonly used data structures in Python are Lists and Dictionaries. Though tuples share a room of similarities with the lists, a few fundamental properties of the latter makes them a popular choice for general programming. I said ‘popular’ and not ‘efficient’. If you are pondering whether tuples are more performant than lists, continue reading. This article aims to deconstruct the performance of tuples.

Lists, Tuples and Properties:

Before exploring the specifics, let us comprehend the basic constructs and differences between a list and a tuple. Both objects store ordered, heterogeneous, and iterable data types, accessible by slicing/indexing. Let us understand these properties through examples.

# Creating a list 'ls'
ls = [1, 2, 3, “Python”, 3.8]
# Creating a tuple 'tp'
tp = (1, 2, 3, “Python”, 3.8)
# The output of the below illustrates the attributes of a list/tuple
for i in range(len(ls)):
print(i)
for i in range(len(tp)):
print(i)
# Output for both ls and tp:
0
1
2
3
4

Ordered: Every element in the list and tuple has ordered indexes (0–4). Heterogeneous: A mix of integer, float and string datatypes are stored. Iterable: Could traverse through the list of elements using a loop. Slicing/Indexing: ‘i’ provides the indexes. Alternatively, ls[0:5] or tp[0:5] is also possible. (the end argument in slicing is not inclusive, hence 5)

It looks like a happy story. What is the conflict? Let me introduce you to ‘mutability’. (definition: liability or tendency to change)

# list
# accessing first element from already created list 'ls'
print(ls[0])
output: 1 # assigning a new value to ls[0]
ls[0] = 0
print(ls)
output: [0, 2, 3, “Python”, 3.8]# tuple
# accessing first element from already created tuple 'tp'
print(tp[0])
output: 1# assigning a new value to tp[0]
tp[0] = 0
TypeError: 'tuple' object does not support item assignment

Yes! Tuples are immutable, a widely understood nuance by the Python coding community. One cannot modify an element in a tuple. But is this a boon or bane? Let’s explore the crucial section of this article.

Memory Management:

To examine the concept in detail, how about we take the help of Python’s library (sys)?

memory and address information using sys library
Output:Tuple tp: (1, 2, 3, ‘Python’, 3.8)
Tuple tp Address: 1702906904392
Tuple tp Memory: 88
— — — — — — — — — — — — — — — — — — — — — — — — —
List ls: [1, 2, 3, ‘Python’, 3.8]
List ls Address: 1702904899144
List ls Memory: 104

The observations we could infer from the above are,

  1. Both tuples and lists reside at unique addresses upon creation.
  2. The lists require more livable space than the tuples. (If you are curious about the reason, share your interest in the comments section. I will write an article.)

To build on this concept, let us create another set of lists and tuples.

lists ls1 and ls2 — memory allocated and address
Output:List ls1 Address:  1856827045000
List ls1 Memory: 80
--------------------------------------------------
List ls2 Address: 1856827045128
List ls2 Memory: 80

Though the code is self-explanatory, we see the initiation of ls1 to [1,2] and re-assignment to 5 in the next step. The focus is on the address of ls1 at the initiation stage, 1856827045000. ls2 is assigned a value of [3,4] with an address 1856827045128. Naturally, the lists ls1 and ls2 have the same length and hence were allocated the same memory, but are stored at different ids/addresses, as inferred earlier.

How about we reproduce the same results using a tuple and have a good look at the output?

Output: Tuple tp1 Address:  1856825281928
Tuple tp1 Memory: 64
--------------------------------------------------
Tuple tp2 Address: 1856825281928
Tuple tp2 Memory: 64

The moment we have been waiting for has arrived. Firstly, tuples require less memory to store the same data. Secondly, in Python, the tuples can be reused. What do I mean by reuse? In the above example, tp1 = (1,2), and we have later changed the value of tp1 to 5. However, the id/address which stored a tuple of length two still exists in the memory. Subsequently, when a tuple tp2 of length two is created, the same id/address is allocated to tp2. Ergo, tuples, tp1 and tp2 point to the same address making them much more efficient than lists. I can now say that “tp2 rented the id/address of tp1.”

Note: You might come across discrepancies such as address mismatch while replicating the above code due to the memory management approaches/optimizations carried out in recent IDEs and python versions. But the overall concept holds true in native Python implementation.

Final Thoughts:

To summarise the article,

  1. Lists and tuples share properties, such as storing ordered, heterogeneous, and iterable data types, accessible by slicing/indexing.
  2. Tuples are immutable, and lists are mutable. One cannot modify a value within a tuple after creation.
  3. The immutable property of tuples makes them more memory efficient and results in faster operations.

Using a suitable data structure for the relevant task is the key. If you are sure of data to remain unchanged with a fixed length, then tuples are favoured. For instance, most of the functions defined in building Python language use tuples directly or indirectly.

I believe you have gained insights into the internal building blocks of tuples. I look forward to publishing more such content in my upcoming articles. Stay tuned.

Happy learning!

--

--

Pradeep Varanasi

Lead Data Scientist at Zensar Technologies | Upgrading the world using Python, R, Machine Learning and Deep Learning