Django: My context variable cannot be used for duplicate for loops

65 Views Asked by At

In views.py I have the variable

mylist = zip(set1,set2,set3)

In templates I do

{% for val1, val2, val3 in mylist%}
{% endfor %}

It works fine. However, if I duplicate the condition it fails. Is it normal? Let's say I have the following:

# this is my page
some text
{% for val1, val2, val3 in mylist %}
  {{forloop.counter}}
{% endfor %}
more text
{% for val1, val2, val3 in mylist %}
  {{forloop.counter}}
{% endfor %}
more text
# final text of page

The first loop will work, and the second one will be empty. It seems as though I can only use once mylist. I didn't experience this issue with simple lists. One solution is to create 2 identical context variables to have 2 for loops but that seems odd...

1

There are 1 best solutions below

0
On BEST ANSWER

Please note that…

The first line of code of your question is odd, I would replace it with:

myzip = zip(mylistA,mylistB,mytuple)

Indeed, a set() is iterable, but it doesn’t have any order. So using zip() in this case results in unexpected behaviour.


The answer

zip() returns an iterator. It can only be consumed once.

Try this as well in python:

myzip = zip([1,2,3], ("a","b","c"))

for i,j in myzip:
    print(i, j)

for i,j in myzip:
    print(i, j)

You’ll get the same behaviour. It will returns the following once:

1 a
2 b
3 c

A work-around is to call the list() function before any for loop:

mylist = list(myzip)