tags:

views:

246

answers:

4

Hi guys

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 if myList is an empty list

Thanks!

+6  A: 
x[index] if len(x) > index else default
gruszczy
this looks to me like the clearest syntax, and it does work for empty list, thanks!
standard caveat: 2.5+ only
Gregg Lind
+4  A: 
try:
   a = b[n]
except IndexError:
   a = default

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

Tim Pietzcker
I like this. Just wrap it around a function so that you can call it with an iterable as an argument. Easier to read.
Noufal Ibrahim
A: 
(L[n:n+1] or [somedefault])[0]
Ignacio Vazquez-Abrams
this won't work for an empty list L
Works fine here.
Ignacio Vazquez-Abrams
sorry you're right, it does work, I prefer the alternative syntax but this is also good
A: 
(a[n:]+[default])[0]

This is probably better as a gets larger

(a[n:n+1]+[default])[0]
gnibbler
Would you write this in actual code without a comment to explain it?
Peter Hansen
@Peter Hansen, only if I was golfing ;) However it does work on _all_ versions of Python. The Accepted answer only works on 2.5+
gnibbler