Joseph Potts
Joseph Potts

Reputation: 191

Python argument counting

I just got into arguments in Python and I find it strange the way the arguments system works in Python (I'm not sure about other languages). For example:

from sys import argv

arg1, arg2, arg3 = argv

print "First argument: ", arg1
print "Second argument: ", arg2
print "Third argument: ", arg3

When I run this in command line with the arguments that follow:

python example.py First Second

It gives the output:

First argument: example.py
Second argument: First
Third argument: Second

Does this mean that python starts counting from zero? Or is there some different or some more reasons it does that. It's odd, but interesting.

Upvotes: 3

Views: 7060

Answers (2)

Levon
Levon

Reputation: 143052

Yes, Python uses zero-based indexing as you surmised (and as many other programming languages also do).

sys.argv is a list of strings.

sys.argv[0] will contain the name of the script, and subsequent entries in this list of strings will contain command line arguments provided to the script.

I was going to provide an example, but what you have in your post is as good as I could come up with.

Finally, as @GregHewgill points out in a helpful comment below, the Python docs provide more information on this as well.

Upvotes: 9

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798814

Arguments have counted from 0 since C with argv, and possibly before then. Argument 0 is the executable/script name, and all the other arguments following it start at 1.

Upvotes: 4

Related Questions