python sys.argv[1] vs. sys.argv[1:]

Question:

I wrote this code:

#!/usr/bin/env python
import sys

if sys.argv[1] :
    print sys.argv[1]

Try this in console when typed:
$ python py.py xxx
that prints xxx
When i leave it with no parameter an error appears:

Traceback (most recent call last): File “py.py”, line 4, in
if sys.argv[1] : IndexError: list index out of range

Now with a few changes:

#!/usr/bin/env python
import sys

if sys.argv[1:] :
    print sys.argv[1:]

You see i changed [1] to [1:] as well and now if i type “$ python py.py ” in console and forget the parameter that returns no error.
Whats happen in the behind the scene?

Asked By: wertvoll

||

Answers:

sys.argv is a list of arguments.
So when you execute your script without any arguments this list which you’re accessing index 1 of is empty and accessing an index of an empty list will raise an IndexError.

With your second block of code you’re doing a list slice and you’re checking if the list slice from index 1 and forward is not empty then print your that slice of the list.
Why this works is because if you have an empty list and doing a slice on it like this, the slice returns an empty list.

last_list = [1,2,3]
if last_list[1:]:
    print last_list[1:]
>> [2,3]

empty_list = []
print empty_list[:1]
>> []
Answered By: Henrik Andersson

sys.argv is a list of arguments (which you passed in along with your command in terminal) but when you are not passing any arguments and accessing the index 1 of the empty list it gives an obvious error (IndexError).
but, in the second case where you are doing slicing from index 1 and using the members of the list with index >1 there should not be a problem even if the list is empty since then the sliced list will also be empty and we get no error.

Answered By: Lavish Saluja
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.