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>To expand this to a much easier, linear solution that works for any n series like this:</p>

<pre><code>def sum_subtract(n):
    return n // 2 * -1 + n % 2 * n
</code></pre>

<p>Every pair of numbers (1 - 2) + (3 - 4) + etc. equals -1, so you just floor divide by 2 and multiply by -1. Next if there is an odd number at the end (n % 2), you add that.</p>

python list