Course contentsShow
← AI Engineering
Lesson 152 of 1,8864. Prompt Engineering FoundationsFree lesson

Loops and Lists in Prompt Templates

Iterate over arrays of items in templates to generate dynamic lists, examples, or multi-turn conversations.

Loops and Lists in Prompt Templates

What you'll learn: How to automatically generate repetitive prompt sections by iterating over lists of data in your templates.

The Core Concept

When building prompts, you often need to include multiple similar items—a list of products, conversation history, or examples. Instead of manually writing each one, you can loop through an array to generate these sections dynamically.

Think of it like a mail merge: you have one template format and a list of recipients. The template repeats for each person, filling in their specific details.

How It Works in Practice

Using Jinja2 (from lesson 149), you write a loop directly in your template:

from jinja2 import Template

template = Template("""
Analyze these customer reviews:
{% for review in reviews %}
- Review {{ loop.index }}: "{{ review }}"
{% endfor %}

Provide a summary.
""")

reviews = ["Great product!", "Arrived damaged", "Perfect fit"]
prompt = template.render(reviews=reviews)

The {% for review in reviews %} block repeats for each item. loop.index gives you the position number.

Common Use Cases

  • Multi-turn conversations: Loop through message history to build context
  • Dynamic examples: Generate few-shot examples from a dataset
  • Batch processing: Create prompts for multiple items in one request
  • Structured data: Format JSON objects, table rows, or bullet points

Key Takeaway: Loops in templates eliminate manual repetition and let you scale prompt generation from arrays of data, making your prompts maintainable and data-driven.