I just learnt of unpacking with the *
and so went on some test runs. I realized that although some write about passing in tuples as arguments in place of positional arguments, I could also pass in strings, lists and sets and Python wouldn't complain as long as I included the *
. I have listed below what I defined as a function taking in positional arguments and the test cases.
What surprised me are the Traceback
s, which led to my question. The Traceback
s mention an IndexError
for a tuple even when none is provided. Is what is happening under the hood a casting of the lists, strings and sets into tuples when the *
is used?
>>> def print2nd(*args):
... print(args[1])
>>> s = "abc"
>>> print2nd(*s)
b
>>> print2nd(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in print2nd
IndexError: tuple index out of range
>>> t = ['a', 'b', 'c']
>>> print2nd(*t)
b
>>> u = set(['a', 'b', 'c'])
>>> print2nd(*u)
a
>>> print2nd(u)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in print2nd
IndexError: tuple index out of range
>>> u[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object does not support indexing
>>> tuple(u)
('b', 'a', 'c')
>>> tuple(u)[1]
'a'