Python Forum
Why args type is always tuple, when passed it as argument to the function. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Why args type is always tuple, when passed it as argument to the function. (/thread-7295.html)



Why args type is always tuple, when passed it as argument to the function. - praveena - Jan-03-2018

I am passing list argument to the function. But type of args is always tuple.
I would like to know the specific reason for this behavior?
>>> def fun(*args):
...     print "type of args :", type(args)
... 
>>> l=[1,2,3,4]
>>> fun(l)
type of args : <type 'tuple'>



RE: Why args type is always tuple, when passed it as argument to the function. - Gribouillis - Jan-03-2018

It is because of the * that you wrote in fun(*args). This * is used when one writes a variadic function that takes a variable number of arguments. If you want to pass a single list argument, use def fun(args).


RE: Why args type is always tuple, when passed it as argument to the function. - praveena - Jan-04-2018

Hi Gribouillis,
Thanks for the replay.
Still my doubt is not cleared. why only tuple is created because of * in fun(*args), why can't list?

Regards,
Praveen.


RE: Why args type is always tuple, when passed it as argument to the function. - Gribouillis - Jan-04-2018

It is the way variadic functions work in python. If you define fun(*args), then you can call
fun(7,8,9) and you have args = (7, 8, 9), a tuple with 3 items. If you call
fun(7), you have args = (7,) a tuple with a single item. Finally, if you call fun([ 3, 4, 5]), then args = ([3, 4, 5],), a tuple which single item is a list.


RE: Why args type is always tuple, when passed it as argument to the function. - wavic - Jan-04-2018

https://docs.python.org/3.6/tutorial/controlflow.html#arbitrary-argument-lists


RE: Why args type is always tuple, when passed it as argument to the function. - praveena - Jan-16-2018

Hi Gribouillis and Wavic,

Thanks for the reply and got clarified.

Regards,
Praveen