The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Popsicle Puzzles

--

Chapters
00:00 How To Get The Nth Element Of A Python List Or A Default If Not Available
00:28 Accepted Answer Score 174
00:41 Answer 2 Score 75
00:53 Answer 3 Score 33
01:00 Answer 4 Score 53
01:22 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]