Predictive Hacks

Hack: elif in list comprehension

We have provided an extensive tutorial of list comprehensions. Sometimes, the syntax of the list comprehensions that deal with if-elif-else conditions can be tricky and that is why we provide an example.

Scenario: You are dealing with product reviews that take values from 1 to 5 and you want to create three categories:

  • Good if the review is greater or equal to 4
  • Neutral if the review is 3
  • Negative if the review is less than 3
x = [1,2,3,4,5,4,3,2,1]

["Good" if i>=4 else "Neutral" if i==3 else "Bad" for i in x]
['Bad', 'Bad', 'Neutral', 'Good', 'Good', 'Good', 'Neutral', 'Bad', 'Bad']

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore