To back up Brenden's (quite correct) answer...
You can actually do some weird things with Python ternary expressions... but the result is just unbearable. Consider a partial solution:
>>> new_list = map(lambda x: x if isinstance(x, int) and (0 <= x and x <= 9) else ValueError('Bad things happened'), [1, 2, 3, "blah"])
>>> list(new_list)
[1, 2, 3, ValueError('Bad things happened',)]
Not only is that horrid and would probably confuse most Pythonistas (not just the use of an unusual construction, but why would you use this construction?), I don't know quite what to do yet about actually raising the exception right there without redefining the way list()
works. (raise
only works when it is standing alone.)
So now we have a confusing lambda that conditionally permits a member into the new map construction or includes a ValueError
object instead. Yuk.
Much better to abstract this whole idea away behind a function that does, in a very simple way, exactly what you want -- and let the "beautiful code part" be the bit people will normally need to read in the future that goes something like:
new_list = valid_list_to_map(your_list)