Christopher Graf
Christopher Graf

Reputation: 2219

Equivalent of Haskell List comprehension example in Python

I was wondering if the following List comprehension example from learnyouahaskell.com can be duplicated in Python:

[ if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x]   

I tried around with something like this, but couldn't get a equivalent to the else path to work in Python's List Comprehension:

["BOOM!" for x in range(7,13) if x < 10] # else "BANG!"

Upvotes: 1

Views: 85

Answers (3)

Haleemur Ali
Haleemur Ali

Reputation: 28233

You can put the if-else as the expression that is evaluated by the comprehension

['BOOM!' if x < 10 else 'BANG!' for x in range(7, 13)]

Upvotes: 1

Azamat Galimzhanov
Azamat Galimzhanov

Reputation: 638

Just move it like this:

["BOOM!" if x < 10 else "BANG!" for x in range(7,13) ]

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

This is not filtering, but a ternary operator that you put in the yield part of the list comprehension. There is however a filter: the odd x part, you thus should add a filter if x % 2 == 1 at the end of the list comprehension:

["BOOM!" if x < 10 else "BANG!" for x in range(7,13) if x % 2 == 1]

In Python this gives us:

>>> ["BOOM!" if x < 10 else "BANG!" for x in range(7,13) if x % 2 == 1]
['BOOM!', 'BOOM!', 'BANG!']

Which is equivalent in Haskell:

Prelude> [ if x < 10 then "BOOM!" else "BANG!" | x <- [7 .. 12], odd x]  
["BOOM!","BOOM!","BANG!"]

Upvotes: 7

Related Questions