Last active
March 10, 2023 18:01
-
-
Save joelburton/93b4923e278e7ef1e6aae2aab90850e0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### 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