How to Toggle a Value?

What is the most efficient way to toggle between 0 and 1?

1

17 Answers

Solution using NOT

If the values are boolean, the fastest approach is to use the not operator:

>>> x = True
>>> x = not x        # toggle
>>> x
False
>>> x = not x        # toggle
>>> x
True
>>> x = not x        # toggle
>>> x
False
Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.