Hack: elif in list comprehension

[This article was first published on Python – Predictive Hacks, and kindly contributed to python-bloggers]. (You can report issue about the content on this page here)
Want to share your content on python-bloggers? click here.

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 such:

  • 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']
To leave a comment for the author, please follow the link and comment on their blog: Python – Predictive Hacks.

Want to share your content on python-bloggers? click here.