0

Can someone please help me understand exactly how the logic is working in below statement of python -

return ["even", "odd"][num % 2]

This function is correctly returning even /odd values.

CDJB
  • 14,043
  • 5
  • 29
  • 55
  • This is explained in some answers here: [Does Python have a ternary conditional operator?](https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator) – Georgy Dec 11 '19 at 14:43

4 Answers4

7

["even", "odd"] is a list with two elements, thus with the indexes 0 and 1.

It is indexed ([]) with num % 2.

If num is even, num % 2 is 0, and ["even", "odd"][0] is "even".

If num is odd, num % 2 is 1, and ["even", "odd"][1] is "odd".

glglgl
  • 89,107
  • 13
  • 149
  • 217
2

The % sign is the mathematical modulus function. num % 2 will return 0 when num is even, and 1 when num is odd. This value is then used to return the corresponding element of ["even", "odd"].

CDJB
  • 14,043
  • 5
  • 29
  • 55
2

It is simply returning a string. The proper value from list ["even", "odd"] is extracted using the remainder(num%2).

For example, let's say num is 4. So, num%2 is 0 . In this case the 0th element of the list (i.e. even) will be returned.

Now if num is 5, the remainder will be 1 and the string in position 1 will be returned (in this case odd). Notice there is no other possible outcome of num%2 even for negative numbers, so no chance of accessing an index which is out of range.

kuro
  • 3,214
  • 3
  • 15
  • 31
2
numbers_list = list(range(10))
def odd_even(any_list):
    odd = []
    even = []
    for element in any_list:
        if element % 2 == 0:
# 10 % 2 = 0, 10 % 3 = 1, 10 / 4 = 2(2) => 10 % 2 = 2
            even.append(element)
        else:
            odd.append(element)
    return odd, even
# there are two way for answers. first - when element % 2 = 0 , so this is even number
# and second - when element % 2 = 1, so this is odd number

print(odd_even(numbers_list))

# if we'll want to run the code output will like this:
# ([1, 3, 5, 7, 9], [0, 2, 4, 6, 8])