I just want to know why this code is generating IndexError: list index out of range
when no argument supplied to it?
script.py
import sys
a = sys.argv[1]
print(a)
Sample output with argument/s
user@linux:~$ python3 script.py abc
abc
user@linux:~$ python3 script.py abc def
abc
user@linux:~$
Sample output without argument/s
user@linux:~$ python3 script.py
Traceback (most recent call last):
File "script.py", line 2, in <module>
a = sys.argv[1]
IndexError: list index out of range
user@linux:~$
My reference: https://www.pythonforbeginners.com/system/python-sys-argv
From the python docs sys.argv
returns:
The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not).
The problem is that when you run your script without arguments like python3 script.py
, you are trying to access the element at index 1
by using sys.argv[1]
but in fact this element doesn't even exists in the list.
Therefore, The python interpreter throws an IndexError
.