This is what it looks like:
first if condition else secondis equivalent to
[second, first][condition]This works because condition will return True or False; True in Python is equivalent to 1 and False is equivalent to 0. We then use this 1 or 0 as the index to a list containing first and second; if the condition returns 0, we get the 0th item of the list: second. If it returns 1, we get the 1st item: first.
Pretty neat, huh?
EDIT 05/08/11: True conditional expressions only evaluate the output term. To get this effect, wrap each term in a lambda and call the entire expression's result.
[lambda: second, lambda: first][condition]()
No comments:
Post a Comment