All Courses

What does the * symbol do in the return statement of a Python function?

By Sde221876@gmail.com, a month ago
  • Bookmark
0

What does the * symbol do in the return statement of a Python function?  

*
Symbol
Return statement
Python
Function
1 Answer
0
Goutamp777

In a Python function, the * symbol in the return statement is used to return multiple values as a tuple. This is known as tuple packing.


For example, consider the following function that takes two arguments and returns their sum and difference:


def sum_and_difference(a, b):
    return a+b, a-b

In this function, the return statement returns two values a+b and a-b separated by a comma. This means that the values will be returned as a tuple, and the tuple will be unpacked into two separate variables when the function is called:


result = sum_and_difference(5, 3)
print(result)  # Output: (8, 2)


sum, diff = sum_and_difference(5, 3)
print(sum)  # Output: 8
print(diff)  # Output: 2

In the second example, the returned tuple is automatically unpacked into the variables sum and diff.

Your Answer

Webinars

Live Masterclass on : "How Machine Get Trained in Machine Learning?"

Mar 30th (7:00 PM) 516 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More