What optimisations are done that this code completes quickly?
<p>I was solving a problem I came across, what is the sum of powers of 3 from 0 to 2009 mod 8.</p>

<p>I got an answer using pen and paper, and tried to verify it with some simple python</p>

<pre><code>print(sum(3**k for k in range(2010)) % 8)
</code></pre>

<p>I was surprised by how quickly it returned an answer. My question is what optimisations or tricks are used by the interpreter to get the answer so quickly?</p>

<p>None, it's just not a lot of computation for a computer to do. </p>

<p>Your code is equivalent to:</p>

<pre><code>&gt;&gt;&gt; a = sum(3**k for k in range(2010))
&gt;&gt;&gt; a % 8
4
</code></pre>

<p><code>a</code> is a 959-digit number - it's just not a large task to ask of a computer.</p>

<p>Try sticking two zeros on the end of the <code>2010</code> and you will see it taking an appreciable amount of time.</p>

python python-3.x optimization