'What is the pythonic way of converting an integer to 1 if nonzero or 0 otherwise
In C the shortest and obvious way to avoid conditions is:
int x = 42;
int oneorzero = !!x; /* Will give us a 1 if x is non-zero or 0 if zero */
Is there a similar way in python?
Solution 1:[1]
I lately used something like
oneorzero = 1 if x else 0
which has the benefit that x is just tested for its truth value and doesn't necessarily need to be 0 for "false".
Solution 2:[2]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | glglgl |
| Solution 2 |
