The provided Python code demonstrates how to return multiple values from a function in Python using tuples. It defines a function named multiple_values() that encapsulates three different values: an integer (value1), a string (value2), and a list (value3). These values are then returned from the function using the return statement. Since multiple values are being returned, Python implicitly packs them into a tuple. Upon calling the function, the returned tuple is unpacked into individual variables (result1, result2, and result3). Finally, the script prints out these returned values, illustrating how multiple values can be efficiently handled and utilized from a single function call in Python. This approach is commonly used when a function needs to provide diverse information to the caller without resorting to more complex data structures or objects.
Source code
def multiple_values():
# Define multiple values
value1 = 10
value2 = 'Hello'
value3 = [1, 2, 3]
# Return multiple values as a tuple
return value1, value2, value3
# Call the function and unpack the returned tuple
result1, result2, result3 = multiple_values()
# Print the returned values
print("Result 1:", result1)
print("Result 2:", result2)
print("Result 3:", result3)
Description
Sure, here’s a step-by-step breakdown of the provided code:
- Function Definition (
multiple_values()):
- Define a function named
multiple_values()without any parameters.
- Variable Assignment within the Function:
- Inside the function, assign three different values to variables:
value1is assigned the integer value10.value2is assigned the string value'Hello'.value3is assigned the list[1, 2, 3].
- Returning Multiple Values:
- Use the
returnstatement to return multiple values from the function. - Since Python allows multiple values to be returned as a tuple, there’s no need to explicitly create a tuple. These values are automatically packed into a tuple.
- Function Call and Unpacking:
- Call the function
multiple_values(). - Assign the returned tuple to three separate variables:
result1,result2, andresult3. - This is known as tuple unpacking, where each element of the tuple is assigned to a separate variable.
- Printing the Returned Values:
- Print out the values stored in the variables
result1,result2, andresult3. - This step demonstrates that the function successfully returned multiple values, and these values are accessible outside the function scope.
In summary, the code defines a function that returns multiple values (an integer, a string, and a list) using the implicit packing of values into a tuple. It then demonstrates how to call the function, unpack the returned tuple, and use the individual values. This approach provides a convenient way to organize and retrieve multiple pieces of data from a single function call.
Screenshot

