Python Forum

Full Version: *args and Tuples
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
def func(*items):
     print(type(items)) 
     a=list(items)
     print(type(a))
     a[3]= 1026
     for i in a:
         print i

items=[1,3,7,9,-99,555,88]
func(*items[:]) 
I am trying to pass a list into *args(*items) and it insists on unpacking it into a tuple, whose immutability makes manipulation of data nigh impossible without converting it into a list.

In all examples I see the default usage of *args is to print, or do some things fairly useless. Being new, I might have overlooked something blazingly obvious - which is why I put this question here:

Is conversion to tuple in *args functions default behaviour for list(array) arguments?
And is there a simple way to call variable arguments and have them default to mutable data types? A decorator?
millpond Wrote:Is conversion to tuple in *args functions default behaviour
Yes python always uses a tuple for the arguments in a function call. If you want a list, just add a line
def func(*items):
    items = list(items)
    ...
Thank you for confirming that suspicion.

I will inscribe:
def func(*items):
items = list(items)

With my biggest, thickest magic marker into my notebook.

In all the books and videos I have on teaching python this fundamental rule has not been mentioned, unless I was braindead while I glossed over it!

Its a critical one for me. For my purposes, tuples make little sense, as mutable lists(arrays) are one of the main purposes for me even bothering to learn python.
millpond Wrote:For my purposes, tuples make little sense
In that case, it may be preferable to use a single array argument, for example
def func(items, spam, eggs):
    items[1] = 3.14

func([10, 11, 12], 'foo', 'bar')
the * args is used to pass a number of arguments. the *items is not the list you created below. tutorial on *args **kwargs
If you want a list passed to your function then just pass a list:
def func(my_list):
    my_list[3]= 1026
    res= []
    for i in my_list:
        res.append(i)
    return res
    
 
items=[1,3,7,9,-99,555,88]
new_item= func(items)
print(new_item)
Output:
[1, 3, 7, 1026, -99, 555, 88]
if a list is not passed then it will throw an error.