Deep Dive into Tuples — Python

Image for post

Tuples are read-only lists whereafter it is created with some elements you cannot add any elements into it. Hence it is called Read Only Lists. Following is an example showing a tuple and how it behaves when you add an element after it is created.

Image for post
Basic Tuple Creation Example

Github link: https://github.com/bvvkrishna/Tuples/blob/master/Tuple%20Basic%20Example.ipynb

Can Tuples be modified?

Tuples can also be modified like lists based on the type of elements added. The following are examples showing how a tuple can be modified.

Image for post
Examples showing Tuple Modification

Github link: https://github.com/bvvkrishna/Tuples/blob/master/Tuple%20Modification%20Example.ipynb

From the above examples, it is evident that we can update tuple with new values. This is possible only when elements in the tuple are Mutable. As you can see all the elements i.e. list, dictionary and sets are mutable data types. Hence we can update tuple.

Let’s go a little deeper and understand why this is possible. The reason is tuples store memory references of its elements and until those references are not modified by any assignment it will not throw any error.

So, in the above examples if we observe we are not adding new elements to a tuple. Instead, the values inside an element (i.e. list, dictionary or set) are getting changed.

How to create a single element Tuple?

Creating one element tuple is tricky and is not straight forward. Following is an example illustrating the same.

Image for post
Creating Single Element Tuple

Github link: https://github.com/bvvkrishna/Tuples/blob/master/1-element%20tuple%20creation%20example.ipynb

In the above examples, the interpreter is identifying a single element as an integer type even though we have used parentheses. Because arithmetic operations can be evaluated in parentheses to prioritize the way expressions are evaluated.

That’s the reason we need to use a different mechanism to represent a single element tuple. Hence we suffixed comma (,) symbol to indicate the element as tuple rather than an integer. I have shown this using an integer number. The same applies when you use other data types like float and strings.

For cool tricks on Python follow me on linkedin –https://www.linkedin.com/in/krishnabvv/