# Unusual ways to check whether number is even (python)

(split from To say weather number is odd or even)

alternative to modulus:

``````x = 3
if x & 1:
print('odd')
else:
print('even')
``````

this directly grabs the last bit of the number in binary, just check whether it’s 0 or 1.

6 Likes

You can use division (`x // 2 * 2` ) and check if it equals `x` . If it does, that means it’s an even number; otherwise, it’s odd. Also, you could compare the integer division of the number by 2 (`x // 2` ) with the result of integer division (`x / 2` ). If they are equal, the number is even; otherwise, it’s odd.

3 Likes

A more convoluted (but original) method would be like so:

``````div2 = lambda x: 1 in [x := abs(x)-2 for _ in range(abs(x)//2+2)]
print(div2(5))``````
1 Like

It does not work for negative numbers. (Also, interesting use of the walrus operator)

2 Likes

oooohh did not know about that ill update it

EDIT: try now!

it does not really work for -2 < x < 2

2 Likes

Try now, itll work. I just updated the range

and yet, the speed benefit is not consistent. So, let’s consider the results which are both more frequent and more dramatic. For larger numbers, I find `&` is slower than `%`. For smaller numbers, `&` wins. Python 3.12:

lol still doesnt work for -2 < x < 2

That is interesting.
One benefit of `&` over `%` is that it rejects all floats.

2 Likes

``````def is_even_bitwise_operator(number):
return (number & 1) == 0
``````
1 Like

I did say that in the original post.
Also, I prefer using `not` over `== 0`

``````def is_even_bitwise_operator(number):
return not (number & 1)
``````
2 Likes

``````div3 = lambda x: float(x//2) == x/2
div4 = lambda x: not x - x//2
div5 = lambda x: x-x//10 in (0, 2, 4, 6, 8. "Never", "Gonna", "Give", "You", "Up)``````
1 Like
``````def div3(x): return x//2 != x/2
def div5(x): return x-(x//10*10) not in (0, 2, 4, 6, 8. "Never", "Gonna", "Give", "You", "Up)
``````

I think `div4` does not work, and I fixed `div5`.

1 Like

Uhh yeah no lol it’ll still syntax error

1 Like

yeah I noticed that but forgot to fix it
the code was wrong though

3 Likes
``````check_even_odd = lambda x: "even" if str(x / 2)[-1] == "0" else "odd"
``````
2 Likes