Python Tuples
Python Tuples Interview Questions
What is a tuple in Python?
A tuple is an ordered, immutable sequence data type in Python. Tuples are defined using parentheses () and can contain elements of different data types. Example: my_tuple = (1, "hello", 3.14).
What does "immutable" mean for tuples?
Immutable means that once a tuple is created, its elements cannot be changed, added, or removed. However, if a tuple contains mutable objects (like lists), those objects can be modified. Example: You cannot do my_tuple[0] = 10.
How to create a tuple with a single element?
To create a tuple with a single element, you must include a trailing comma: single_tuple = (5,). Without the comma, Python interprets (5) as just the integer 5.
What is tuple packing and unpacking?
Tuple packing: Creating a tuple by assigning multiple values: t = 1, 2, 3. Tuple unpacking: Extracting values from a tuple into variables: a, b, c = t. You can also use the asterisk (*) for extended unpacking.
How is a tuple different from a list?
1. Tuples are immutable, lists are mutable. 2. Tuples use parentheses (), lists use square brackets []. 3. Tuples are generally faster than lists. 4. Tuples can be used as dictionary keys, lists cannot.
What are the advantages of using tuples over lists?
1. Tuples are faster than lists. 2. Tuples can be used as dictionary keys (if all elements are immutable). 3. Tuples protect data from accidental modification. 4. Tuples use less memory than lists.
Can you modify a tuple after creation?
No, you cannot directly modify a tuple's elements. However, you can create a new tuple by concatenating or slicing existing tuples. Also, if a tuple contains mutable objects (like lists), those objects can be modified.
How to access elements in a tuple?
You can access tuple elements using indexing (starts at 0) and slicing. Example: my_tuple[0] gets the first element, my_tuple[1:3] gets elements from index 1 to 2. Negative indexing also works: my_tuple[-1].
What tuple methods are available in Python?
Tuples have only two built-in methods: count() - returns the number of occurrences of a value, and index() - returns the index of the first occurrence of a value.
Can a tuple be used as a dictionary key?
Yes, tuples can be used as dictionary keys if all elements in the tuple are immutable (strings, numbers, other tuples). Example: my_dict = {(1, 2): "value"} is valid, but {(1, [2, 3]): "value"} is not.
What is namedtuple in Python?
namedtuple is a factory function from the collections module that creates tuple subclasses with named fields. It makes code more readable: Point = namedtuple('Point', ['x', 'y']), then p = Point(10, 20) and access with p.x.
How to concatenate tuples?
Use the + operator to concatenate tuples: tuple1 = (1, 2), tuple2 = (3, 4), result = tuple1 + tuple2 gives (1, 2, 3, 4). This creates a new tuple.
How to repeat a tuple?
Use the * operator to repeat a tuple: my_tuple = (1, 2), repeated = my_tuple * 3 gives (1, 2, 1, 2, 1, 2).
What is the significance of tuples in function returns?
Functions can return multiple values using tuples. Python packs the return values into a tuple. Example: def get_coordinates(): return 10, 20 returns (10, 20). The caller can unpack: x, y = get_coordinates().
How to check if an element exists in a tuple?
Use the in operator: my_tuple = (1, 2, 3), if 2 in my_tuple: print("Found"). This works similarly to lists and other sequences.
What is tuple comprehension?
Python doesn't have tuple comprehension like list comprehension. However, you can create a tuple using a generator expression inside tuple(): squares = tuple(x*x for x in range(5)) gives (0, 1, 4, 9, 16).
How to convert a list to a tuple?
Use the tuple() constructor: my_list = [1, 2, 3], my_tuple = tuple(my_list) gives (1, 2, 3). This creates a new tuple with the same elements.
What happens when you try to modify a tuple element?
Python raises a TypeError with the message: "'tuple' object does not support item assignment". This is because tuples are immutable.
Can tuples contain mutable objects?
Yes, tuples can contain mutable objects like lists, dictionaries, or sets. While the tuple itself is immutable (you can't add/remove elements), the mutable objects inside can be modified.
What is the use of tuples in real-world applications?
1. Returning multiple values from functions. 2. As dictionary keys (for hashable elements). 3. Storing constant data. 4. In database operations (records). 5. For function arguments (args, kwargs). 6. In threading (immutable data is thread-safe).
Why is (1) not a one-tuple?
Parentheses group expressions—integer 1. Use trailing comma: (1,).
Empty tuple syntax?
() or tuple()—(,) is invalid.
When is a tuple hashable?
If every element is hashable—lists inside tuples block hashing.
Mutable object inside tuple—can you change it?
Yes—the tuple references stay fixed but list contents can mutate—breaks hashability if that inner list changes.
tuple([1,2,3]) copies?
Creates new tuple from iterable—elements shared if mutable objects.
Unpacking a, *rest = seq—rules?
Star captures remainder list—must match unpack arity rules.
namedtuple._replace?
namedtuple._replace returns a new instance—named tuples are immutable; fields are updated via replacement, not item assignment.
Tuple vs list memory footprint?
Tuples often slightly smaller and faster for fixed heterogenous records—implementation detail but interview talking point.
Lexicographic tuple comparison?
Element-wise like strings—(1, 10) > (1, 2) True.
Tuple as dict key—requirements?
Must be hashable—tuple of strings OK; tuple containing list illegal.
x, y = y, x uses tuples?
Tuple packing/unpacking—rotation without temp thanks to evaluation semantics.
TypeError modifying tuple element?
Item assignment forbidden—immutability is structural for the tuple container.
tuple.count / index?
Same spirit as list—linear search for index.
(f(),)—comma saves?
Ensures single-element tuple even when expression looks like grouping.
collections.namedtuple vs plain tuple?
Named fields improve readability—still immutable records.
Why tuples for function multiple returns?
Packing values is cheap and immutable snapshot semantics communicate fixed arity groups.
zip rows as tuples?
Each yielded row is tuple—convenient relational pairing.
Singleton tuple in arithmetic?
Still wrap carefully—comma disambiguates from parens for math precedence.
sys.getsizeof tuple vs list same length?
Tuples often smaller overhead—good for large static tables.
Nested tuples hash?
Only if all nested components recursively hashable.
typing.NamedTuple vs dict row?
Stronger structure for static tooling—still tuple subclass.
Tuple in set?
Allowed if hashable—duplicate tuples equal by value collapse in set.
Slicing tuple—copy?
New tuple object—elements references copied shallowly.
for a, b in pairs requires?
Each item iterable length 2—ValueError otherwise.
Why immutable default args sometimes tuples?
Share safe read-only config—never use mutable lists as defaults.
itertools.product yields?
Tuples of combinations—Cartesian structure.
Tuple concatenation creates?
New tuple—doesn’t mutate operands.
max(tuple) empty?
ValueError—same as list.
Star-args def f(*args) type?
args is tuple of positional captures.
Final: equality (1, [2]) == (1, [2])?
True by value—but nested list breaks hashing—tuple overall unhashable.
Note: Tuples are an essential Python data structure that provides immutability, performance benefits, and safety for data that shouldn't change. Understanding tuples is crucial for writing efficient, thread-safe Python code. They're particularly useful for returning multiple values from functions and as dictionary keys.