Alternate between add and subtract on a list of numbers
<p>How to get the sum of the series 1-2+3-4+5-6+7-8+9-10 in python? </p>

<p>I know how to get the sum of numbers from 1 to a particular number by using while loop in this way:</p>

<pre><code>i = 1
sum = 0
while i&lt;= 10:
    sum = sum + i
    i = i + 1
print(sum)
</code></pre>

<p>You can use a generator expression like </p>

<pre><code>&gt;&gt;&gt; sum(v if v%2 else -v for v in range(11))
-5
</code></pre>

<p>Here we check if the index is even or odd and add the number accordingly. </p>

<p>Another way can be using the <code>zip</code> builtin, But this works only for an even range. </p>

<pre><code>&gt;&gt;&gt; sum(x-y for x,y in zip(l[::2],l[1::2]))
-5
</code></pre>

<p>You can avoid slices and reduce the code size by using <code>iter</code>. <code>iter</code> creates an iterator that'll be exhausted whenever it has been called. </p>

<pre><code>&gt;&gt;&gt; i = iter(l)
&gt;&gt;&gt; sum(x-y for x,y in zip(i,i))
-5
</code></pre>

python list