The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Thinking It Over

--

Chapters
00:00 Question
00:38 Accepted answer (Score 159)
00:54 Answer 2 (Score 71)
01:10 Answer 3 (Score 47)
01:52 Answer 4 (Score 46)
02:38 Thank you

--

Full question
https://stackoverflow.com/questions/2492...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list

#avk47



ACCEPTED ANSWER

Score 174


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



ANSWER 2

Score 75


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

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




ANSWER 3

Score 53


(a[n:]+[default])[0]

This is probably better as a gets larger

(a[n:n+1]+[default])[0]

This works because if a[n:] is an empty list if n => len(a)

Here is an example of how this works with range(5)

>>> range(5)[3:4]
[3]
>>> range(5)[4:5]
[4]
>>> range(5)[5:6]
[]
>>> range(5)[6:7]
[]

And the full expression

>>> (range(5)[3:4]+[999])[0]
3
>>> (range(5)[4:5]+[999])[0]
4
>>> (range(5)[5:6]+[999])[0]
999
>>> (range(5)[6:7]+[999])[0]
999



ANSWER 4

Score 33


(L[n:n+1] or [somedefault])[0]