Reputation: 9054
I have
if board[a][b] == 0:
board[a][b] = chr(current_char)
I want to refactor into one line. Something like the following:
board[a][b] = chr(current_char) if board[a][b] == 0
It seems that the closest I can come to this is
board[a][b] = chr(current_char) if board[a][b] == 0 else board[a][b]
But the else clause seems redundant. Is there a stylistically better way to accomplish this?
Upvotes: 2
Views: 527
Reputation: 5291
You can do this in Python:
if board[a][b] == 0: board[a][b] = chr(current_char)
if all you intend is to put this in one line.
Upvotes: 2
Reputation: 2161
Your two line version is easily the clearest. Stick with it.
>>> board[a][b] = board[a][b] or chr(current_char)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
What just happened here? If your manager wrote it, you want to find a new manager. If you did, maybe your manager will be looking for a new employee, since the program crashed while you were on vacation.
Upvotes: -1
Reputation: 77107
Oldschool Python had a trick for doing the ternary before Python had a ternary operator. Actually, this trick will work in many programming languages. I'm only going to tell you if you promise not to use it.
Promise?
[val_if_false, val_if_true][bool(condition)]
OK, now Python has a ternary, which looks like
val_if_true if condition else val_if_false
But even that is kinda sloppy. If you really want a one liner, make a function.
def val():
if condition:
return val_if_true
else:
return val_if_false
Your specific case is a little more specialized, since you want the else
to be the original value. You could do
box[a][b] = box[a][b] or chr(current_char)
But again, the if
statement is just more readable and clear as to the intent.
Upvotes: 7
Reputation:
A more "Pythonic" way of doing this type of thing is:
board[a][b] = board[a][b] or chr(current_char)
Upvotes: 2