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>Given you are trying to alternate the sign you can use the fact that <code>(-1)**n</code> also alternates the sign. But you want a negative when <code>n</code> is even you will need <code>(-1)**(n-1)</code>:</p>

<pre><code>&gt;&gt;&gt; list(n*(-1)**(n-1) for n in range(1, 11))
[1, -2, 3, -4, 5, -6, 7, -8, 9, -10]
&gt;&gt;&gt; sum(n*(-1)**(n-1) for n in range(1, 11))
-5
</code></pre>

<p>This can be turned into an explicit looping solution with:</p>

<pre><code>t = 0
for n in range(1, 11):
    t += n*(-1)**(n-1)
print(t) # -5
</code></pre>

python list