How to Implement enumerate()  in Odoo?
What is enumerate()?
Python’s enumerate() function adds a counter/index to an iterable (like a list or recordset), allowing you to loop with both index and value.
✅ Syntax
for index, value in enumerate(iterable, start=0):     # use index and value python_obj = json.loads(json_string)
  • iterable: A list, tuple, or Odoo recordset.
  • start: Optional index to start counting from (default is 0).

📌 Realistic Use Cases in Odoo

1. Numbering Items in a List (e.g., in Report or Email Body)

Suppose you’re preparing a message with numbered order lines:

body = “Order Lines:\n”

for idx, line in enumerate(self.order_line, start=1):

    body += f“{idx}. {line.product_id.name} – Qty: {line.product_uom_qty}\n”

self.message_post(body=body)

This creates a structured, user-friendly message with line numbers.

2. Generate Indexed Data in Excel Export

When exporting product lines to Excel:​

row = 2

for idx, line in enumerate(order.order_line, start=1):

    sheet.write(row, 0, idx)  # Serial number

    sheet.write(row, 1, line.product_id.name)

    sheet.write(row, 2, line.product_uom_qty)

    row += 1​

You provide a clear, indexed list in the export file.

3. Detecting First Record in a Loop

Sometimes you need to treat the first item differently:

for idx, partner in enumerate(partners):

    if idx == 0:

        _logger.info(“Primary partner: %s”, partner.name)

    else:

        _logger.info(“Secondary partner: %s”, partner.name)

✅ Summary Table

Function Purpose Example Use Case
enumerate() Loop with index and value Numbering order lines, Excel serials
start parameter Set custom starting index Start from 1 instead of 0