Q1. What is a tuple in Python?
A tuple is an immutable, ordered collection of items. Created with parentheses ().
Example:
Tuples are often used for fixed data and as dictionary keys (since they are hashable).
Example:
tup = (1, 2, 3) Once created, its elements cannot be changed.Tuples are often used for fixed data and as dictionary keys (since they are hashable).
Q2. What is the difference between a list and a tuple?
Lists are mutable, tuples are immutable.
Lists use more memory, tuples are more memory-efficient.
Lists have methods like append, remove; tuples have only count and index.
Tuples can be used as dictionary keys, lists cannot.
Both are ordered sequences.
Lists use more memory, tuples are more memory-efficient.
Lists have methods like append, remove; tuples have only count and index.
Tuples can be used as dictionary keys, lists cannot.
Both are ordered sequences.
Q3. How do you create a single-element tuple?
A single-element tuple requires a trailing comma.
Example:
Empty tuple: ()
Example:
t = (5,) Without comma, it's just an integer in parentheses.Empty tuple: ()
Q4. What is tuple unpacking?
Tuple unpacking assigns elements of a tuple to multiple variables.
Example:
It works with any iterable.
Example:
a, b = (1, 2) This is often used to swap variables: a, b = b, a.It works with any iterable.
Q5. When would you use a tuple over a list?
Use tuples when data should not change (e.g., coordinates, configuration constants).
They are also more memory-efficient and can be used as keys in dictionaries.
For functions returning multiple values, tuples are natural.
They are also more memory-efficient and can be used as keys in dictionaries.
For functions returning multiple values, tuples are natural.
