1

There are several answers to what Python's splat operator does (unpack lists or tuples into separate args inside the called function) but I can't find anything about the interesting side effect of how the splat operator coerces lists to tuples (effectively rendering passing a list with splat as being passed by value, not reference).

So, is it true that Python's splat operator coerces lists into tuples:

def test(*arg):
    print(type(arg))
    for a in arg:
        print(a)

lst = ['roger', 'colleen']
print(type(lst))
test(*lst)         

tpl = ('roger', 'colleen')
print(type(tpl))
test(*tpl)

It seems to. The code above produces this output:

<class 'list'>
<class 'tuple'>
roger
colleen
<class 'tuple'>
<class 'tuple'>
roger
colleen

I'm trying to solidify my knowledge of lists and tuples. I read here that

The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.

I was at first surprised that calling test() with a list didn't let test() change the list (they aren't immutable). But they are when passed with the splat operator to function because they get coerced to a tuple. Right? I think!

Update: rkersh's comments said something that adds a lot of clarity:

test(*arg) isn't being called with a list, it's being called with the items in the list)--and those items are seen by *arg as a tuple.

rp.
  • 17,483
  • 12
  • 63
  • 79
  • In particular, the top answer there says "yes", and links to the section of the official tutorial which says the same. – Dan Getz May 22 '16 at 16:21
  • 1
    The *star expression* `*` unpack the iterable. It doesn't modify it. – styvane May 22 '16 at 16:22
  • Try this : def test(*arg): print(type(*arg)) for a in arg: print(a) – Sivaswami Jeganathan May 22 '16 at 16:34
  • KART, 'type(*arg)' fails with TypeError: type() takes one or three arguments. (using Python3) – rp. May 22 '16 at 16:40
  • 1
    You aren't calling test() with a list. You're calling test with the items from a list (the `*` operator unpacks them). Then, in the test function, arg captures these items in a tuple. – rkersh May 22 '16 at 17:00
  • rkersh--that is a great answer. Calling test' with the items in the list' is well-stated and makes what's happening very clear. – rp. May 22 '16 at 17:02

0 Answers0