How to get the nth element of a python list or a default if not available


Question

I'm looking for an equivalent in python of dictionary.get(key, default) for lists. Is there any one liner idiom to get the nth element of a list or a default value if not available?

For example, given a list myList I would like to get myList[0], or 5 ifmyList is an empty list.

Thanks.

1
125
7/22/2018 6:37:05 AM

Accepted Answer

l[index] if index < len(l) else default

To support negative indices we can use:

l[index] if -len(l) <= index < len(l) else default
106
6/20/2018 7:48:55 PM

try:
   a = b[n]
except IndexError:
   a = default

Edit: I removed the check for TypeError - probably better to let the caller handle this.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon