0

Learning list comprehensions and discovered that if/if-else statement can be placed in different order of apperance in expression. In example, starting understanding list comprehension construction from for loop schema:

positive = []
for number in numbers:
    if int(number) >= 0:
        positive.append(int(number))
    else:
        positive.append(0 - int(number))

can be evaluated to:

positive = [int(number) if int(number) >= 0 else 0 - int(number) for number in numbers]

But

positive = []
for number in number:
    if int(number) >= 0:
        positive.append(int(number))

goes to:

positive = [int(number) for number in numbers if int(number) >= 0]

I know that one of useful technique for creating list comprehension is to read for loop from top to down and put them in one line (a little shortcut of course). But why those 2 examples put if / if-else statement once in front and secondly in the end of construction?

  • In the first example, the `if` and `else` are not actually part of the list comprehension. They are just a conditional expression used as the value. – mkrieger1 May 21 '20 at 21:29

1 Answers1

1

In the first case, you're choosing between two options; but in either choice, you're adding to the list. Whatever comes before the for is added to the list.

In the second case, you're only adding to the result list in one option. Whatever comes after the for construct on the right decides if something is added at all.


If you want to pick what's added between (usually two) options, use the first. If you what to pick if something is added at all, use the second.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117