vendredi 17 août 2018

Why is else required in if statements inside some list comprehensions?

When defining a list of items, why do you need an else statement to accompany any if statements? For example, using Python 3.7 say that we have some condition which could be true or false, and we want to include an element in a list if the condition is true, and not include it if it's false.

condition = False
lyst = ['a', 'b', 'c' if condition]

I would expect it to assign ['a', 'b'] to lyst, but it throws a syntax error. It works if we include an else statement:

lyst = ['a', 'b', 'c' if condition else 'd']

But now the result is that lyst = ['a', 'b', 'd'] In this question, user Plankton's answer further specifies that you can't use a "pass" in the else statement. My question is why the else statement is required? Is it so that the list that gets created is guaranteed to have the number of items expected? If so, this strikes me as not very pythonic.

This is particularly weird because you can have if statements without else statements in list comprehensions in some cases, such as:

post = [x for x in range(10) if x > 5]
# equivalent to: post = [6, 7, 8, 9]

Is the difference that in the last example, the condition applies to all elements in the list?

Aucun commentaire:

Enregistrer un commentaire