Is there a pythonic way to make python ignore IndexError
and just return a default value or None
when I access a list/array with an out-of-range index?
import sys
input = sys.argv[1]
output = sys.argv[2]
This may cause IndexError
when the program is run with no more than 2 parameters. However if I want to say that there are default values for argv[1]
and argv[2]
, then I should write like:
import sys
input = len(sys.argv) > 1 ? sys.argv[1] : DefaultValue1
output = len(sys.argv) > 2 ? sys.argv[2] : DefaultValue2
Is there any pythonic way to shorten this statements exept try
?
(like name = input or "Not set"
for pythonic null-colaescing operator)