0

I'm still new to python. Some of the exercises I'm working on are things like 'return a list of integers up to but less than n' or 'return a list of odd (or even) integers up to but less than n', etc.

Seems reasonably straight-forward, and I was able to understand how to make a short function that does these things. For example, for generating a list of odd numbers...

def odds(n)
    return [i for i in range(n) if (i % 2 == 1)]

... works just fine.

But the suggested solution was:

def odds(n)
    return [i for i in range(n) if i % 2]

This returns the same thing. But I don't understand the 'if i % 2' at the end. How can this work when we haven't clarified what the 'i % 2' test needs to evaluate to???

Dragon-Ash
  • 71
  • 1
  • 1
  • 9

1 Answers1

0

because in python booleans are just integers, 0 is False and any other number is True So when you say if i % 2 the same as if you say if i % 2 != 0, if it equals 0 then it's false and it won't do anything, but if it's anything other than false 0 it will push i to the list

EDIT: try to do something like this:

if 1:
    print("True")
else:
    print("False")

Then try it with 0 and you'll see the difference.

AM Z
  • 423
  • 2
  • 9
  • So can I understand it as basically that 'if i % 2' defaults to testing whether it is True? – Dragon-Ash Aug 23 '20 at 00:08
  • Yes, expressions that require a boolean, like "if" will essentially automatically wrap the given object in bool(). – Bobby Ocean Aug 23 '20 at 00:17
  • @Dragon-Ash Yes, it's just testing if it's anything other than 0 and if it is, then it'll be true otherwise it's false – AM Z Aug 23 '20 at 00:21
  • @Dragon-Ash Let's assume that i is 5, so 5 % 2 = 1 "in int" which is True, but if it's an even number like 4 then it'll be 0 because 4 % 2 = 0 so it's False – AM Z Aug 23 '20 at 00:23