Question 13: Unpacking Tuples in Function Arguments

This quiz question tests your understanding of unpacking tuples in function arguments in Python.

You should know how to use the * operator to unpack tuples and handle function parameters effectively.

Question: Tuples in Function Arguments

Consider the function calculate_area which takes two parameters, length and width, and returns the area of a rectangle.

You have a tuple dimensions containing the length and width of a rectangle.

def calculate_area(length, width):
    return length * width

dimensions = (5, 10)

Which of the following code snippets incorrectly uses the calculate_area function to calculate the area using the values in the dimensions tuple?















Option A is the correct answer.

  • Explanation: The function calculate_area expects two separate arguments, length and width, but this code passes a single tuple, leading to a TypeError.
  • Result:
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    area = calculate_area(dimensions)
TypeError: calculate_area() missing 1 required positional argument: 'width'

Option B:

  • Reason for Incorrectness: The * operator unpacks the tuple into separate arguments, so calculate_area receives 5 as length and 10 as width.
  • This is the correct and concise way to call the function with the values in the tuple.
  • Result: area = 50

Option C:

  • Reason for Incorrectness: This correctly unpacks the tuple into individual values for length and width.
  • However, it unnecessarily complicates the code with explicit indexing when the unpacking (*) operator is more straightforward.
  • Result: area = 50 (but not the preferred method)

Option D:

  • Reason for Incorrectness: This code unpacks the tuple into two variables, length and width, and then calls calculate_area with these variables.
  • This method is correct and clear, showing a good understanding of tuple unpacking.
  • Result: area = 50

Leave a Reply