Skip to content

Instantly share code, notes, and snippets.

@joelburton
Last active March 10, 2023 18:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelburton/93b4923e278e7ef1e6aae2aab90850e0 to your computer and use it in GitHub Desktop.
Save joelburton/93b4923e278e7ef1e6aae2aab90850e0 to your computer and use it in GitHub Desktop.
### WAYS TO LOOP OVER TWO THINGS AT ONCE IN PYTHON:
cats = ["fluffy", "puffy", "muffy"]
dogs = ["fido", "rover", "bowser"]
# jinja-specific way, won't work in regular python:
#
# {% for cat in cats %}
# {{ cat }} {{ dogs[loop.index0] }}
# {% endfor %}
# ways that you can do this in regular python:
# basic and works fine:
for i in range(len(cats)):
print(f"{cats[i]} and {dogs[i]}")
# loop, getting the item *and* the index (similar to JS' map/filter):
for (i, cat) in enumerate(cats):
print(f"{cat} and {dogs[i]}")
# using neat built-in function zip, which gives a tuple of both as each loop item:
for cat_and_dog in zip(cats, dogs):
print(f"{cat_and_dog[0]} and {cat_and_dog[1]}")
# same, but using unpacking (JS: "destructuring") while looping:
for (cat, dog) in zip(cats, dogs):
print(f"{cat} and {dog}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment