List vs Tuple
Today we are going to learn about the difference between List and Tuple in Python.
List is one of the most widely used data types in Python. When it comes to Tuple it has similar properties to List.
List vs Tuple
- Both are used for storing heterogeneous data which means that any kind of data type can be stored.
- Both are ordered, keeping the order of items which are put into it.
- Both are sequential data types, we can iterate over the item using loops.
So, how do they differ?
The key difference between the tuples and lists is tuples are immutable objects and the lists are mutable which means that tuples cannot be changed while the lists can be modified.
As tuples are immutable the memory allocated for tuples is fixed and memory allocated for list is more when compared with tuples.
So that tuples are more memory efficient.
Let’s compare memory allocation,
sample_list = [1, 2, 3,4, 5] sample_tuple = (1, 2, 3, 4, 5) print(“Size of list: ”, sample_list.__sizeof__()) print(“Size of tuple: ”, sample_tuple.__sizeof__())
Size of list: 80 Size of tuple: 64
So, from the output it is clear that memory allocation for the list is more than tuple.
- The literal syntax of tuples is shown by parentheses () whereas the literal syntax of lists is shown by square brackets  .
- Lists have variable length, tuple has fixed length.
- List has mutable nature, tuple has immutable nature.
- Since lists are variable in length, it needs more memory than tuple.