isar
isar

Reputation: 1791

Invert boolean assignment in one line

Is there a short way to do this:

if flag == False:
    flag = True

I feel like it should be only a few letters.
I'm also curious about how other languages tackle this condition-assignment. Thank you.

Edit

If flag is True it needs to stay True therefore I can't use flag = not flag.
flat = True is indeed a one-line solution but since the statement is inside a loop I'm not sure if reassigning flat = True every time is good practice.

Upvotes: 0

Views: 3774

Answers (3)

Ryuzaki L
Ryuzaki L

Reputation: 40048

By using if-else do it in one line either True or `False

flag = True if 10<5 else False #(True if condition is True else False)

Upvotes: 1

Bigbob556677
Bigbob556677

Reputation: 2158

For inline conditionals in general you could use

if flag ==  False: flag = True

or for just toggling a boolean you could use

flag = not flag

you could also use the ternary operator which is something like

flag = condition_if_true if condition else condition_if_false

Upvotes: 0

ritlew
ritlew

Reputation: 1682

Yes! You can simply invert it with a short expression:

flag = not flag

Upvotes: 0

Related Questions