Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value at list/array index or "None" if out of range in Python

Tags:

python

Is there clean way to get the value at a list index or None if the index is out or range in Python?

The obvious way to do it would be this:

if len(the_list) > i:     return the_list[i] else:     return None 

However, the verbosity reduces code readability. Is there a clean, simple, one-liner that can be used instead?

like image 861
Chris Dutrow Avatar asked Aug 29 '12 20:08

Chris Dutrow


People also ask

What to do if list index is out of range Python?

“List index out of range” error occurs in Python when we try to access an undefined element from the list. The only way to avoid this error is to mention the indexes of list elements properly.

What does list index return if not found?

The index() method searches for the first occurrence of the given item and returns its index. If specified item is not found, it raises 'ValueError' exception.

Does Python have index out of bounds?

This error basically means you are trying to access a value at a List index which is out of bounds i.e greater than the last index of the list or less than the least index in the list. So the first element is 0, second is 1, so on.

Can I put none in a list Python?

To replace none in python, we use different techniques such as DataFrame, fillna, or Series. No keyword in python declares the null objects and variables. In python, none refers to the class 'NoneType'. We can allot None to many variables, and they all point toward a similar object.


2 Answers

Try:

try:     return the_list[i] except IndexError:     return None 

Or, one liner:

l[i] if i < len(l) else None 

Example:

>>> l=list(range(5)) >>> i=6 >>> print(l[i] if i < len(l) else None) None >>> i=2 >>> print(l[i] if i < len(l) else None) 2 
like image 184
the wolf Avatar answered Sep 20 '22 16:09

the wolf


I find list slices good for this:

>>> x = [1, 2, 3] >>> a = x [1:2] >>> a [2] >>> b = x [4:5] >>> b [] 

So, always access x[i:i+1], if you want x[i]. You'll get a list with the required element if it exists. Otherwise, you get an empty list.

like image 41
Hashken Avatar answered Sep 19 '22 16:09

Hashken