Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
List and Tuple are the most commonly used data structure in the Python programming language. As these two data structures are pretty much similar, it is not really an easy task for beginners to differentiate their use cases. In this article, we will be mainly focusing on the key differences between lists and tuples by analyzing their properties and use cases.
Let’s start with a little introduction to the list and tuple.
Source: Giphy
List
The list is one type of mutable container that can store different types of data elements and iterate over the elements. It can be considered as one type ofdynamic array in C.
Example
eg_list=[1,2,'Python',4]
You can also try this code with Online Python Compiler
As lists are mutable, when we need to extend the size of the list, extra allocation of memory is required. But as a tuple is immutable, the minimum memory block is allocated for it. In that context, the tuple is more memory efficient than lists.
eg_list=[1,2,'Python',4]
eg_tuple=(4,5,'tuple',4)
print('size of list=',eg_list.__sizeof__())
print('size of tuple=',eg_tuple.__sizeof__())
You can also try this code with Online Python Compiler
You can practice by yourself with the help of online python compiler for better understanding.
Use cases
Lists are mainly used when data or the size of the container can be changed during runtime. But tuple is only used to store static data set. The list can not be used as the key indictionarydata structure due to its mutable property, but a tuple can be used as a key.
Built-in methods
Many built-in methods like insert, pop, sort or remove, and reverse are associated with the list. But such inbuilt functions are not available for tuples.
## find associated functions for each types
dir(eg_list)
dir(eg_tuple)
You can also try this code with Online Python Compiler
A tuple is faster than a list as for a tuple, memory is allocated from a single memory block, but for a list, memory is allocated from different chunks which are linked.
Is it possible to store the list in a tuple or vice-versa?
Yes, it is possible to store lists as elements of a tuple and vice versa.
Is it possible to modify the list stored in a tuple?
If a tuple contains a single list, it can’t be modified. But if there are multiple inner lists, then inner lists can be modified separately.
Conclusion
This article covered the comparison between lists and tuples by describing their properties through code snippets.
Also, refer to the other two data structures of python, i.e.,Dictionary and Sets.