Search code examples
pythonreturn

What is * in return function in python?


What is * in return (last line of code)?

def func_list():
    arr=[x for x in range(1,6,2)]
    arr1=arr
    arr1.append(10)
    return *arr,

print(func_list())

after run this code, return value is:

(1, 3, 5, 10)


Solution

  • This behaviour is explained by PEP 448 "Additional Unpacking Generalizations".

    Asterisks were previously used for argument unpacking in function calls and in function argument declarations.

    With the implementation of PEP 448 in Python 3.5, as the PEP states, unpacking is allowed also in "tuple, list, set, and dictionary displays".

    This mean one can use an asterisk to unpack some values when creating e.g. a tuple. The PEP shows this example:

    >>> *range(4), 4
    (0, 1, 2, 3, 4)
    

    In the question, the unpacking was used in a similar way, when creating a tuple. That is actually why there is a coma at the end of the line - that makes it a tuple, so unpacking is allowed there.

    return *arr,
    

    That said, I would not suggest using this the way it was done in the question. For that use case, return tuple(arr) would be much cleaner IMO, if a tuple needs to be returned.