0

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)

mSafdel
  • 1,527
  • 4
  • 15
  • 25

2 Answers2

2

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.

zvone
  • 18,045
  • 3
  • 49
  • 77
2

The * operator unpacks a list (or any other iterable). In your example:

return *arr,

There is actually a much more important symbol that changes the meaning of the expression: The comma. Commas in python are a bit odd. Take this example:

a = 1,

It might surprise you that a == (1,) The comma creates a tuple. In python tuples don't actually need parenthesis. However, if they have only a single element they need a trailing comma.

This is why your function returns a tuple.

As for the *, it will unpack a iterable. For example you can run print(*range(100)) to print the numbers between 1 and 100. You can also use [*l] to easily shallow copy a list l.

The * effectively unwraps copies the contents of a iterable. It can be used in function arguments, sets, tuples, lists, and even on the left-hand side of a assignment.

All combined, *l, copies the contents of l to a tuple.

mousetail
  • 7,009
  • 4
  • 25
  • 45