How to Implement one line for loop with if and else in Odoo?

Overview

In Python, a one-liner for loop with conditional logic is called a list comprehension (or dictionary/set comprehension). It is used to build new collections (like lists) from an iterable, in a compact and readable form.

✅ Basic Syntax

[<expression_if_true> if <condition> else <expression_if_false> for <item> in <iterable>]

This will evaluate each item and apply either the if_true or else part accordingly.

📌 Example

[ “Even” if x % 2 == 0 else “Odd” for x in range(5) ]

# Output: [‘Even’, ‘Odd’, ‘Even’, ‘Odd’, ‘Even’]

🧠 Realistic Use Case in Odoo

Suppose you want to get a list of partner names with a suffix based on whether they have an email:

partners = self.env[‘res.partner’].search([])

names = [

    partner.name + (‘ ✅’ if partner.email else ‘ ❌’)

    for partner in partners

]

This creates a list of partner names with a check mark if they have an email, or a cross if they do not.

✅ Summary Table

Element
Description
for x in y Standard loop
if condition else Adds conditional logic per item
Usage Clean, efficient conditional collections