0

My problem is that I want to read a list (with a for loop) which is inside a tuple like this:

items = {a, b, [1, 2, 3]}

'a' and 'b' are other data I need.

Now for reading a list I do this, which doesn't work:

{% for item in items.3 %}
  {{item}}
{% endfor %}

So my question is how can I read, with a for loop, a list which is inside a tuple?

Thanks for the help.

tkowal
  • 9,129
  • 1
  • 27
  • 51
Daan Mouha
  • 580
  • 1
  • 6
  • 20

2 Answers2

2

Python indexes in lists/tuples are started from zero. So you should use the index 2:

{% for item in items.2 %}
  {{ item }}
{% endfor %}

BTW, tuples are defined with round brackets, not the curly:

items = (a, b, [1, 2, 3])
catavaran
  • 44,703
  • 8
  • 98
  • 85
  • It didn't work. If I type {{items.0}}, I get errors. I get curly brackets even in django. I think because I work with Erlang in the underlaying code. – Daan Mouha Feb 20 '15 at 09:57
  • 1
    Curly brackets in python is a shortcut for define a `set`. Python sets are not indexed, so `{1, 2, 3}[0]` will raise the error. And of course a tuple `(1, 2, 3)[0]` will work fine. – catavaran Feb 20 '15 at 10:14
  • I cracked the case. But I don't know what the problem was. I deleted everything of that part of code and started over. Now it just works fine. Thanks for the help any way. – Daan Mouha Feb 20 '15 at 10:21
0

I just deleted the part of code and started over. An extra tip: If the list in the tuple is a list of tuples and you want to read a part of the tuple. You have to use a new for loop to read it.

For example, I have this:

items = {a, b, [{1, 2, 3}, {4, 5, 6}]}

Now for getting a list out of a tuple:

{% for item in items.3 %}
    {{item}}
{% endfor %}

Now for getting something out of the tuple from the list

I try to do this but it doesn't work, if there are people who know how to fix this, please add a comment:

{% for item in items %}
    {{item.1}}
{% endfor %}

This is my trick to get it done:

{% for item in items %}
    {% for i in item %}
        {{i}}
    {% endfor %}
{% endfor %}

To get the counter of the outer most loop check this post: how-to-access-outermost-forloop-counter-with-nested-for-loops-in-django-template

Thanks

Community
  • 1
  • 1
Daan Mouha
  • 580
  • 1
  • 6
  • 20