1

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)

Related post? (using or operator)

KYHSGeekCode
  • 1,068
  • 2
  • 12
  • 30

2 Answers2

1

Unsure whether this is really pythonic, but you could extend sys.argv with an array containing None and slice it. Then you just have to test the values against None:

input, output = (sys.argv + [None] * 2)[:2]
if input is None: input = defaultValue1
if output is None: output = defaultValue2

Or in a one liner:

defaultValues = [defaultValue1, defaultValue2]
input, output = (val if val is not None else defaultValues[i]
                 for i, val in enumerate((sys.argv + [None] * 2)[:2]))

Close to a matter of taste...

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

Set your deafult values in default_val_a and default_val_b and set your index in index a is your sys.arg[1] and b is your sys.arg[2]. This is the most pythonic and single line way that i can come up:

import sys

a = [1]
b = []

default_val_a = [1, 2, 3]
default_val_b = [4, 5, 6]

index = 1

a = default_val_a[index] if len(a) <= index or not a else a[index]
b = default_val_b[index] if len(b) <= index or not b else b[index]

print(a, b)

And the structure is like that:

VAR = DEFAULT_VALUE[INDEX] if len(VAR) <= INDEX or not VAR else VAR[INDEX]
Gokhan Gerdan
  • 1,222
  • 6
  • 19