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]
No, Python doesn’t have any shorthands or simplifications to the
try/exceptsyntax.To solve your specific problem, I would probably use something like:
Which would avoid the need for an exception.
Or to get super cool and generic:
Alternative, you could use:
itertools.iziplongestto do something similar:Finally, one small note on nomenclature:
iis traditionally used to mean “index”, so usingfor i, j in enumerate(…)would be more “normal”.