user14998540
user14998540

Reputation:

Determine odd or even in a list, return results to a new list

The exercise I have is asking me to determine if each number of a list is even or odd, then to return the result in a new list named is_even.

My code

num_lst = [3, 20, -1, 9, 10]
is_even = []
for n in num_lst:
    if n % 2 == 0:
        n = is_even.append(bool(n))
    else :
        is_even.append(bool(0))
print(is_even)

It works, but is there a better way to do it ?

Upvotes: 2

Views: 906

Answers (4)

Ouroborus
Ouroborus

Reputation: 16875

Bit-wise operators are preferred for even/odd detection:

num_lst = [3, 20, -1, 9, 10]
is_even = [not num & 1 for num in num_lst]
print(is_even)

Numbers that are odd have their least significant bit set so use & 1 to mask to just that bit. not conveniently coerces to boolean and inverts the results.

Upvotes: 2

Anis R.
Anis R.

Reputation: 6912

In your current code, you are checking the value of a boolean expression, n % 2 == 0, which will evaluate to either True or False depending on n. Then, there is no need to say "if true, then append True, and if false, then append False. So, a slight rewording of your existing code is to directly call is_even.append(n % 2 == 0) in your for loop:

for n in num_lst:
    is_even.append(n % 2 == 0)

This can be further shortened using a list comprehension, as per @marcdtheking's answer, into something like:

is_even = [n % 2 == 0 for n in num_lst]

Side note: At some point in your code you are appending bool(n), with n being your list element. So basically you are converting your number into a boolean. This can be error prone, e.g. if n is zero, bool(0) is False, while zero is an even number. Why not using True and False instead of bool(n) and bool(0)?

Upvotes: 1

pakpe
pakpe

Reputation: 5479

If you haven't learned about list comprehensions yet, your code is perfectly fine. You can simplify it slightly by simply using True and False. Also see the answer by Anis.

num_lst = [3, 20, -1, 9, 10]
is_even = []
for n in num_lst:
    if n % 2 == 0:
        n = is_even.append(True)
    else :
        is_even.append(False)
print(is_even)

Upvotes: 1

I break things
I break things

Reputation: 326

Yeah, use a list comprehension

>>> num_lst = [3, 20, -1, 9, 10]
>>> is_even=[bool(0) if i % 2 else bool(i) for i in num_lst]
>>> print(is_even)
[False, True, False, False, True]

Upvotes: -1

Related Questions