Issue
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.
Solution
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
Answered By - gruszczy Answer Checked By - Candace Johnson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.