Why are variables persisting inside of my for loop?
This is totally normal and expected behavior. In fact, it's critical for some looping situations, and pretty standard across programming languages. Wouldn't you expect to find this same behavior in PHP?

Think about situations where previous loops build on each other. Here's an example of a situation where loop values need to be retained...

{% set totalPets = 0 %}

{% for petOwner in craft.entries.section('petOwners').find %}

    {% set totalPets = totalPets + petOwner.numberOwned %}

{% endfor %}

&lt;p&gt;This group of people owns {{ totalPets }} pets total.&lt;/p&gt;


Ultimately, this is a simple scope issue. Generally speaking, for loops don't exist in their own scope... they are a part of the scope created by the parent script.

If you want to ensure that your logic takes place in a separate scope, take a look into Twig macros... A macro would probably be very helpful in your situation.