How to get the nth element of a python list or a default if not available
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puddle Jumping Looping
--
Chapters
00:00 How To Get The Nth Element Of A Python List Or A Default If Not Available
00:31 Accepted Answer Score 172
00:49 Answer 2 Score 75
01:05 Answer 3 Score 51
01:39 Answer 4 Score 51
02:21 Answer 5 Score 32
02:29 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
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puddle Jumping Looping
--
Chapters
00:00 How To Get The Nth Element Of A Python List Or A Default If Not Available
00:31 Accepted Answer Score 172
00:49 Answer 2 Score 75
01:05 Answer 3 Score 51
01:39 Answer 4 Score 51
02:21 Answer 5 Score 32
02:29 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]