Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Comments on Why are list comprehensions written differently if you use `else`?

Parent

Why are list comprehensions written differently if you use `else`?

+14
−0

The following list comprehension worked when I tried it:

[num for num in hand if num != 11]

But this doesn't work:

[num for num in hand if num != 11 else 22]

It gives a SyntaxError, highlighting the else.

This led me to believe that you can't use else in a list comprehension. However, I then discovered that this is possible instead:

[num if num != 11 else 22 for num in hand]

Why does the if need to be placed earlier in the comprehension in order to include a matching else?

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.
Why should this post be closed?

0 comment threads

Post
+19
−0

It's not a matter of order; Python simply does not directly allow else clauses as part of list comprehensions (docs). When we use

[num if num != 11 else 22 for num in hand]

We are actually using Python's version of the ternary operator; the if and else are not part of the list comprehension itself but of the comprehension expression. That is, the above is actually

[(num if num != 11 else 22) for num in hand]
History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.

1 comment thread

To add, the if at the end of the list comprehension is a predicate (3 comments)
To add, the if at the end of the list comprehension is a predicate
elgonzo‭ wrote almost 3 years ago · edited almost 3 years ago

To add, the if expression at the end of the list comprehension (behind the iterable / element emitter) is a filter predicate, determining whether an iterated / emitted element will take part in the comprehension. That means, it has to be boolean expression. if num != 11 else 22 is not a boolean expression, hence it is not suitable as a predicate to determine whether an element partakes in list comprehension...

Unfortunately, the (official) Python doc is rather vague and unspecific in documenting/explaining this... :-(

elgonzo‭ wrote almost 3 years ago · edited almost 3 years ago

Self-deprecating pedantry: Realizing the nature of the predicate, technically else clauses can appear directly in the predicate expression -- albeit in a colossally stupid and useless way, for example by translating the boolean expression num != 11 into the equivalent form True if num != 11 else False, turning the list comprehension into the hilarious wonder that is [num for num in hand if (True if num != 11 else False)]. Yes, it's still not in the way the author of the Q actually intended to utilize else, but I am nevertheless going to claim "Mission accomplished" and pat myself on my shoulder now for the next 5 minutes... ;-P (;_;)

hkotsubo‭ wrote almost 3 years ago

elgonzo‭ To add a little bit more pedantry, the filter predicate doesn't have to be exactly a boolean, because in Python any object can be tested for truth value. Which means I can do this:

values = ['abc', '', [], ['123'], 10, 0, range(0), range(1, 2)]
# "if s" checks if "s" is a truthy value
print([ s for s in values if s ])

And this will print ['abc', ['123'], 10, range(1, 2)].

Anyway, that's beside the point of the question (using else in list comprehension).