Menu Close

How to iterating through two lists in Python Django templates?

To iterating through two lists in Python Django templates, we can zip the lists in our view and pass the zipped list into our template.

For instance, we write

mylist = zip(list1, list2)
context = {
            'mylist': mylist,
        }
return render(request, 'template.html', context)

to zip list1 and list2 into one with zip and assign it to mylist.

And then we call render with the context dict to pass the mylist value to the template.html template.

Then in template.html, we add

{% for item1, item2 in mylist %}

to loop through mylist with a for loop.

Posted in Python, Python Answers