Take the 2-minute tour ×

Is there a way to fall back to an empty value if there are no elements in a certain index of the array

foo_val = int(data_arr[3])

IndexError: list index out of range

share|improve this question
So you want something like a default value? –  Volatility Jan 24 '13 at 11:44
yes, a default value –  Sam Jan 24 '13 at 12:06
What default value do you want to use?. –  Michael J. Barber Jan 24 '13 at 12:18
say 0 as the default –  Sam Jan 24 '13 at 12:30

3 Answers 3

up vote 0 down vote accepted

alternate to try except:

Its one line instead of 4, and is still readable:

foo_val = int(data_arr[3]) if len(data_arr) >= 4 else 0

note that len is not zero indexed hence >=4 instead of >=3

share|improve this answer
You mean len <= 4? –  Volatility Jan 24 '13 at 12:12
nope. we are saying give item at index 3 if data_arr has 4 or more items items in it. If not then fallback to 'fallback value' –  rikAtee Jan 24 '13 at 12:17
Oh of course, my mistake ;) –  Volatility Jan 24 '13 at 12:19

Use try and except.

try: # Try doing this piece of code
    foo_val = int(data_arr[3])
except IndexError: # If there is an IndexError, do this piece of code.
    foo_val = 0
share|improve this answer
no this won't be acceptable, as there would be many such values. –  Sam Jan 24 '13 at 12:07
@Sam How does the amount of such values matter? How does it prevent you from using this? –  user1632861 Jan 24 '13 at 12:46

You could use a defaultdict from the collections module:

dd = collections.defaultdict(int) # default to zero, change as needed
for n, x in enumerate(data_arr):
    dd[n] = x
dd[len(data_arr) + 10] # IndexError for data_arr, returns 0 with defaultdict

You can also do this with just a dict, by using the get method to provide the default value, but a defaultdict is a little more convenient.

share|improve this answer

Your Answer


