Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of star operator when used on List [duplicate]

Tags:

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'> 
like image 383
Joel Avatar asked Nov 10 '11 09:11

Joel


People also ask

What is the use of * operator in 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.

What does * in front of list mean in Python?

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.

What is the use of * operator in association with list in Python?

It multiplies a list by copying its item references (not the items).

What does double star mean in Python?

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.


2 Answers

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").

like image 183
Frédéric Hamidi Avatar answered Oct 20 '22 05:10

Frédéric Hamidi


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.

like image 37
eumiro Avatar answered Oct 20 '22 07:10

eumiro