Range function behavior in jinja2

I’m getting someone unexpected behavior with the range function and upon searching I found this unit test page. If I paste the following in the template designer

{% for i in range(5, 10) %}{{ i }} {% endfor %}

It yields

5 6 7 8 9 

Which matches the output shown on the page’s Jinja2 section. My question is why is this returning one less than the right-most element passed to the range function?

1 Like

That’s normal behaviour in most programming languages, because most of them start index at 0 and not at 1.
If you do for i in range(3), you get 0,1,2

It’s normal for arrays, lists and other such structures to start at 0, but I can’t think of a single language where your start a counter at 1 and it reverts to 0. E.g. in C#

for (int i=1;i <=10;i ++)
   Write(i);

Would print the following because i is initialized to start at 1.

1,2,3,4,5,6,7,8,9,10

You doctored that normal C# for loop. The auto-completed for-loop in C# defaults to < which yields the same result as range(10).

Anyways, in python, range has always behaved this way. Jinja is based on python.

1 Like

Yeah, another reason python sucks. Range(5…10) implies the range is, well 5-10.

You’re welcome to do everything long hand the way C# does it.

i = 5
while i <= 10:
   i++