description |
---|
Practice writing list comprehension, using Jinja, to create a new list from existing list data |
💡 List comprehension (a special enhancement to "Rewst-flavored Jinja"!) allows you to create a new list from an existing one in a simplified way, without needing to end the code with {% endfor %}
. It consists of three parts:
- Output – What do you want in your new list?
- For Loop – How do you loop through data in the original list?
- Condition (Optional) – Do you need to filter items to include in your new list?
Here's the basic structure:
{{
[ output for output
in CTX.list
if condition ]}}
{% embed url="https://youtu.be/bvCXCyCl5rE?si=X0djxKF7Jduux1nL" %}
Additional Tips
- Use dot notation in the output to specify parts of each item.
- The condition (typically, an "if" statement) is optional and filters based on criteria like "if the color is not red."
- If you want to turn the list into a string, apply the "join" filter. You'll find an example of this in the "Lunch Menu" exercises for this lesson.
For a few examples, refer to the Jinja List Comprehension Examples module.
Practice the list comprehension exercises included in the "Lunch Menu" data set: #lesson-resources
Go to the previous module: | basic-jinja-syntax-and-filters.md | |
Go to the next module: | jinja-list-comprehension-examples-them-apples.md |