0

I am trying to understand how *args works as a parameter of a function/method.

>>> l
['1', '2', '3']
>>> def test(*args):
    print(type(args))
    for arg in args:
        print(arg)


>>> test(*l)
<class 'tuple'>
1
2
3
>>> m = *l
SyntaxError: can't use starred expression here

I get SyntaxError when I try to assign *l to a variable but when I pass the same to function test() it works just fine. I want to understand how is this working with function and why do i get SyntaxError when I try to do the same and assign it to a variable instead.

Afaq
  • 1,146
  • 1
  • 13
  • 25
  • what would expect the value of `m` to be in `m = *l`? I certainly couldn't be a single value since your trying to unpack `l`, and it wouldn't make sense to make `m` a list since `m = l.copy()` does the exact same thing. – Christian Dean Apr 05 '17 at 03:43
  • I expect it to work just like the same when i passed it to `test()` and get a `tuple` maybe. But yes my final aim is not to get a tuple but to understand why it fails when i do `m = *l` and how it works when i pass the same `*l` to function `test()`. – Afaq Apr 05 '17 at 03:45
  • 1
    It fails because it only works that way with a function. Period. – Ignacio Vazquez-Abrams Apr 05 '17 at 03:49
  • 1
    @Afaq When using `*args` in a function, Python handles that behind the scenes. It doesn't work when you do it alone because it doesn't make sense for the reasons I described above. – Christian Dean Apr 05 '17 at 03:50

0 Answers0