Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
*args and Tuples
#1
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?
Reply
#2
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)
    ...
Reply
#3
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.
Reply
#4
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')
Reply
#5
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020