This is the most common interview question in an interview and a lot of students are only able to give one difference but you can also think that if you want to look separate from the crowd then you have to tell all the differences are there. don’t worry after reading this article you will be able to give the right answer to this question. In this article, I showed you all differences between List and Tuple.
1. Creation
List – A list is a comma-separated value in square brackets and a square bracket is mandatory.
data = [‘jay’, 23, 30000]
Tuple – Tuple is comma separated value in parenthesis and parenthesis is optional.
data = (‘jay’, 23, 30000)
2. Mutable.
- List is Mutable.
- Tuple is Immutable.
l = [23, 46, 79, 45, 34]
t = (23, 34, 56, 78, 89)
# Here i am trying to change list value of 46 to 60 lets see what happen
l[1]= 60
print(l)
# Here i am trying to change tuple value 34 to 50 lets see what happen
t[1] = 50
print(t)
3. Memory Consumption
- Tuple object takes less memory than list object for same data.
- List is slow in execution than tuple
- List is less efficient in memory utilization than tuple.
Code –
import sys
l = [‘hello’, 12, 23.5, 2+3j]
t = (‘hello’, 12, 23.5, 2+3j)
print(sys.getsizeof(l))
print(sys.getsizeof(t))
Here you can see that list has taken 88 and tuple has taken 72 which is less than List.
4. Comprehension Concept
The comprehension concept is applicable only for list and not for tuple
5. Packing and Unpacking
- List Supports packing but not support unpacking.
- Tuple supports both packing and Unpacking.
Read More Post –