What is the star operator doing to the input argument list in this example?
def main(name, data_dir='.'): print 'name', type(name) if __name__ == '__main__': main(*sys.argv)
Concretely, if I run the program with the star operator it prints:
name <type 'str'>
if run without the star main(sys.argv)
it prints:
name <type 'list'>
The star(*) operator unpacks the sequence/collection into positional arguments. So if you have a list and want to pass the items of that list as arguments for each position as they are there in the list, instead of indexing each element individually, you could just use the * operator.
The asterisk (star) operator is used in Python with more than one meaning attached to it. For numeric data types, * is used as multiplication operator >>> a=10;b=20 >>> a*b 200 >>> a=1.5; b=2.5; >>> a*b 3.75 >>> a=2+3j; b=3+2j >>> a*b 13j.
It multiplies a list by copying its item references (not the items).
Argument with double asterisks (stars) is used in function definition when variable number of keyword arguments have to be passed to a function >>> def function(**arg): for i in arg: print (i,arg[i]) >>> function(a=1, b=2, c=3, d=4) a 1 b 2 c 3 d 4.
The *
operator unpacks an argument list. It allows you to call a function with the list items as individual arguments.
For instance, if sys.argv
is ["./foo", "bar", "quux"]
, main(*sys.argv)
is equivalent to main("./foo", "bar", "quux")
.
main(*sys.argv)
calls main
with the content of the list sys.argv
as respective arguments of the main
method and is in this case equivalent to:
main(sys.argv[0])
or
main(sys.argv[0], sys.argv[1])
depending on the length of sys.argv
.
So if you call it with the asterisk, it passes to name
the first element of the list sys.argv
.
If you call it without the asterisk, it passes to name
the whole list sys.argv
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With