28

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'>
Joel
  • 29,538
  • 35
  • 110
  • 138

2 Answers2

53

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

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
3
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.

eumiro
  • 207,213
  • 34
  • 299
  • 261
  • But @Frédéric Hamidi showed the entire list instead of first argument. Why not just main("./foo") instead of main("./foo", "bar", "quux")? – user2994783 Sep 29 '21 at 23:25