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 should do like:</p>

<pre><code>i = 1
my_sum = 0
while i&lt;= 10:
    if i % 2:  # True, if i is divisible by 2
        my_sum -= i
    else:
        my_sum += i 
    i += 1  # same as i = i + 1
</code></pre>

<p>Some other alternative approaches:</p>

<pre><code>&gt;&gt;&gt; sum((i if i % 2  else -i) for i in range(1, 11))
-5
&gt;&gt;&gt; sum(map(lambda x: x if x %2 else -x, range(1, 11)))
-5
</code></pre>

python list