Getting the default value for an index out of range in Python

a=['123','2',4] b=a[4] or 'sss' print b 

I want to get the default value when the list index is out of range (here: 'sss' ).

How can i do this?

+57
python list syntax default-value
Apr 04 '10 at 14:10
source share
13 answers

In the spirit of Python, “asking for forgiveness, not permission”, here is one way:

 try: b = a[4] except IndexError: b = 'sss' 
+68
Apr 04 '10 at 14:13
source share

In a non-Python spirit, “asking for permission, not forgiveness,” is another way:

 b = a[4] if len(a) > 4 else 'sss' 
+48
Apr 04 '10 at 14:15
source share

In the Python spirit of beauty is better than ugly

Code golf method using slice and unpack

 b=a[4:4+1] or 'sss' 

Nothing than a wrapper or try-catch function IMHO, but intimidating for beginners. Personally, I think that unpacking a set will be more sexual than a list [#]

using cutting without unpacking:

 b,=a[4:5] or ['sss'] 

or, if you need to do this often, and don't mind making a dictionary

 d = dict(enumerate(a)) b=d.get(4,'sss') 
+14
Mar 27 '14 at 10:47
source share

You can create your own list class:

 class MyList(list): def get(self, index, default=None): return self[index] if len(self) > index else default 

You can use it as follows:

 >>> l = MyList(['a', 'b', 'c']) >>> l.get(1) 'b' >>> l.get(9, 'no') 'no' 
+11
Feb 28 '13 at 15:08
source share

another way:

 b = (a[4:]+['sss'])[0] 
+9
Feb 18 '15 at 12:46
source share

You can also define a small helper function for these cases:

 def default(x, e, y): try: return x() except e: return y 

Returns the return value of function x if it did not raise an exception of type e ; in this case, it returns y . Using:

 b = default(lambda: a[4], IndexError, 'sss') 

Change Only one specified exception is blocked.

Suggestions for improvement are still welcome!

+6
Apr 04 '10 at
source share
 try: b = a[4] except IndexError: b = 'sss' 

A cleaner way (only works if you use a dict):

 b = a.get(4,"sss") # exact same thing as above 

Here you might like another way (again, only for dicts):

 b = a.setdefault(4,"sss") # if a[4] exists, returns that, otherwise sets a[4] to "sss" and returns "sss" 
+3
Apr 04 '10 at 14:14
source share

Im all for permission request (i.e. I don't like try ... except method). However, when it is encapsulated in a method, the code becomes much cleaner:

 def get_at(array, index, default): if index < 0: index += len(array) if index < 0: raise IndexError('list index out of range') return array[index] if index < len(a) else default b = get_at(a, 4, 'sss') 
+1
Apr 04 '10 at 14:27
source share

For the usual case, when you want the first element, you can do

 next(iter([1, 2, 3]), None) 

I use this to “expand” the list, perhaps after filtering it.

 next((x for x in [1, 3, 5] if x % 2 == 0), None) 

or

 cur.execute("SELECT field FROM table") next(cur.fetchone(), None) 
+1
Mar 26 '14 at 17:49
source share

Using try / catch?

 try: b=a[4] except IndexError: b='sss' 
0
Apr 04 '10 at 14:14
source share

Since this is Google’s top hit, it’s probably worth mentioning that the standard “collection” package has a “defaultdict” that provides a more flexible solution to this problem.

You can do neat things, for example:

 twodee = collections.defaultdict(dict) twodee["the horizontal"]["the vertical"] = "we control" 

More details: http://docs.python.org/2/library/collections.html

0
Feb 16 '13 at 2:21
source share

If you are looking for a convenient way to get the default values ​​for an index operator, I found the following useful:

If you override operator.getitem from the operator module to add an optional default parameter, you will get identical behavior with the original while maintaining backward compatibility.

 def getitem(iterable, index, default=None): import operator try: return operator.getitem(iterable, index) except IndexError: return default 
0
Jan 20 '16 at 14:03
source share

If you are looking for a quick hack to reduce character code length, you can try this.

 a=['123','2',4] a.append('sss') #Default value n=5 #Index you want to access max_index=len(a)-1 b=a[min(max_index, n)] print(b) 

But this trick is only useful when you no longer want to make changes to the list.

-one
Nov 02 '16 at 5:57
source share



All Articles