Interview question
What is the difference between a list and a tuple in Python? Python में list और tuple में क्या अंतर है?
Answer
| Aspect | List | Tuple |
|---|---|---|
| Mutability | Mutable - can change after creation | Immutable - cannot change |
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Performance | Slightly slower | Faster, less memory overhead |
| Use case | Data that changes (dynamic collections) | Fixed data, dictionary keys |
my_list = [1, 2, 3]
my_list.append(4) # works fine
my_list[0] = 99 # works fine
my_tuple = (1, 2, 3)
# my_tuple.append(4) # AttributeError
# my_tuple[0] = 99 # TypeError
# Tuples can be dict keys, lists cannot
locations = {(28.7, 77.1): 'Delhi'} # works
# {[28.7, 77.1]: 'Delhi'} # TypeError - unhashable| पहलू | List | Tuple |
|---|---|---|
| Mutability | Mutable | Immutable |
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Performance | थोड़ा धीमा | तेज़, कम memory |
| Use case | बदलने वाला data | Fixed data, dict keys |
my_list = [1, 2, 3]
my_list.append(4)
my_list[0] = 99
my_tuple = (1, 2, 3)
# my_tuple.append(4) # AttributeError
# my_tuple[0] = 99 # TypeErrorWas this answer clear?