Simply a try/except with lambda - Python?

alvas picture alvas · Jan 8, 2013 · Viewed 8.7k times · Source

Is there a way to simplify this try/except into a one line with lambda?

alist = ['foo','bar','duh']

for j,i in enumerate(alist):
  try:
    iplus1 = i+alist[j+1]
  except IndexError:
    iplus1 = ""

Is there other way other than:

j = '' if IndexError else trg[pos] 

Answer

David Wolever picture David Wolever · Jan 8, 2013

No, Python doesn't have any shorthands or simplifications to the try/except syntax.

To solve your specific problem, I would probably use something like:

for j, i in enumerate(alist[:-1]):
   iplus1 = i + alist[j + 1]

Which would avoid the need for an exception.

Or to get super cool and generic:

from itertools import islice

for j, i in enumerate(islice(alist, -1)):
    iplus1 = i + alist[j + 1]

Alternative, you could use: itertools.iziplongest to do something similar:

for i, x in itertools.izip_longest(alist, alist[1:], fillvalue=None):
    iplus1 = i + x if x is not None else ""

Finally, one small note on nomenclature: i is traditionally used to mean "index", so using for i, j in enumerate(…) would be more "normal".