What is the difference between List and Tuple in python?
List:
List is Mutable (i.e can be changed).
Use Square brackets like [].
Slightly slower than tuple due to dynamic nature.
Either use Dynamic data change.
Tuple:
Tuple is Immutable (i.e cannot be changed)
Use Parentheses like ()
Faster and Safer due to immutability.
Either use fixed data Or constant change.
Real Time Example:
- List
my_list = [1, 2, 3]
my_list[0] = 100 # ✅ Allowed
print(my_list)
=> Output: [100, 2, 3]
- Tuple
my_tuple = (1, 2, 3)
my_tuple[0] = 100 # ❌ TypeError: 'tuple' object does not support item assignment
No comments:
Post a Comment