Sure, here's a Python interview question:
Question: What is the difference between a list and a tuple in Python?
Answer: In Python, both lists and tuples are used to store collections of items, but they have some key differences:
Mutability: Lists are mutable, which means you can add, remove or change elements after the list has been created. Tuples, on the other hand, are immutable, which means you cannot change elements once the tuple has been created.
Syntax: Lists are defined using square brackets [], while tuples are defined using parentheses (). For example,
my_list = [1, 2, 3]
andmy_tuple = (1, 2, 3)
.Performance: Since tuples are immutable, they are generally faster and more memory-efficient than lists. In cases where you don't need to modify the elements in the collection, using a tuple can be a good option.
Usage: Lists are typically used for collections of items where you need to add or remove elements frequently, or where you need to modify elements. Tuples are typically used for collections of items that are fixed and won't change, or where you want to ensure that the collection is not modified accidentally.
It's important to note that while tuples are immutable, they can still contain mutable objects such as lists or dictionaries. This means that you can modify the contents of a list or dictionary that is stored inside a tuple, even though you can't modify the tuple itself.
Post a Comment