Why doesn't the else work in this situation

Viewed 63

For an assignment I need to do these two exercises:

  1. create a list that includes multiplying each number from 1 to 9 (included) by 100, only if it divides with 2 with no remainder.

  2. create a list that includes multiplying each number from 1 to 9 (included) by 100, only if it divides with 2 with no remainder.if there is a remainder leave the number as is, don't multiply by 100.

Answer 1 worked:

list_1 = [num * 100 for (num) in range(1,10) if num % 2 == 0]

print (list_1)

But why doesn't the answer for exercise 2 work?:

list_1 = [num * 100 for (num) in range(1,10) if num % 2 == 0 else num]

print (list_1)
4 Answers

You can do;

In [1]: [x * 100 if x % 2 == 0 else x for x in range(1, 10)]
Out[1]: [1, 200, 3, 400, 5, 600, 7, 800, 9]

Write it like this:

list_1 = [num * 100 if num % 2 == 0 else num for num in range(1,10)]

You can do something like this:

list_1 = [(num * 100  if num % 2 == 0 else num) for (num) in range(1,10)]

Which evaluates the statement x if y else z as the output for each list element. Hope this helps :)

Your alternation is switched all around.

[x for x in xs if some_predicate else y]

parses as

[(x for x in xs) if some_predicate else (y)]  # which makes no sense

Not as

[(x) for x in xs if some_predicate else (y)]

But you can do

[x if some_predicate else y for x in xs]
Related