0

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.

4
  • 10
    Isn't that just flag = True? Commented Nov 20, 2018 at 18:53
  • 1
    (Assuming, of course, that flag was previously either False or True. Also, comparing to False with == is pretty much always either unnecessary or wrong.) Commented Nov 20, 2018 at 18:53
  • flag = not flag...at least I think that's what your asking for Commented Nov 20, 2018 at 18:53
  • You're making the classic newbie mistake of putting in more work to avoid an assignment than you actually save. Assignment is cheap. Heck, you're still performing the assignment in the answer you accepted; the accepted answer is strictly more expensive than flag = True. Commented Nov 20, 2018 at 21:42

3 Answers 3

1

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

Ya but in the above code there in no loop, and it completely depends on your requirement, everytime if you need to check condition then it is necessary, or if the requirement is just to assign flag once based on condition, then place it outside of loop
0

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

flag = not flag 

3 Comments

Python doesn't use !.
but if flag is True this code will set it to False.
According to the title I thought they were looking for a way to invert a boolean with one line
0

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.