🐍 Python
Beginner
What is the difference between a list and a tuple in Python?
Answer
Both lists and tuples are ordered sequences that can hold items of any type. The key difference is mutability. A list ([1, 2, 3]) is mutable — you can add, remove, and change elements after creation. A tuple ((1, 2, 3)) is immutable — once created, it cannot be changed. Tuples are slightly faster than lists, use less memory, and can be used as dictionary keys (since they are hashable). Use tuples for fixed collections of heterogeneous data (like a record or coordinates) and lists for homogeneous sequences that may change. Named tuples (collections.namedtuple) add field names to tuples without the overhead of a full class.
Previous
What are Python's key data types?
Next
What is the difference between a list and a dictionary?