0

I was looking at a youtube tutorial and saw someone use this syntax (I don't remember the name of the video or who made it because it was weeks ago, but, it's something like this):

bar(*variable)

What I've observed while messing around with the * operator.

nums = [1, 2, 3]
foo(*nums) # Assuming foo has only one argument, throws an error saying it expects 1 argument, not 3.

So if I have a foo function with 3 arguments foo(a, b, c) then passing in foo(*nums) will work just fine. Another example is the asyncio.gather() function with has an argument called *aws which lets me do this:

asyncio.gather(*coros)

Its quite handy since I can't pass in a list of coroutine objects (my knowledge on asyncio is rusty, so don't mind the incorrect terms, but, feel free to correct me). So that makes it very useful. I have tried at guess what it does. From messing around like this:

nums = [1, 2, 3]
print(*nums)
# 1, 2, 3

It seems to just do "quick unpacking"? I can also do

nums = [1, 2, 3]
a, *b = nums # lets me store the rest of the values in b
print(a) # 1
print(b) # [2, 3]

From what I can see it just allows for quick unpacking. And to pass in lists as function arguments in an unconventional way. And I've also not seen the * operator used a lot. So I'm very curious as to what it really does, and it's actual application.

YJH16120
  • 419
  • 1
  • 4
  • 15
  • I voted to reopen the question, this is specifically about the use "outside function", the question linked as duplicate is purely about "inside function call". – Meitham Feb 06 '21 at 14:04
  • I'm pretty sure the Python documentation covers the use of the `*` operator both inside and outside of functions. Maybe the OP should start [here](https://docs.python.org/3/genindex-Symbols.html), look at all the docs related to `*`, and come back if something was unclear. – larsks Feb 06 '21 at 14:27

0 Answers0