Python Sys.argv[1] Vs. Sys.argv[1:]
Solution 1:
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]
>> []
Solution 2:
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.
Post a Comment for "Python Sys.argv[1] Vs. Sys.argv[1:]"