creating sum of odd indexes python
<p>I'm trying to create a function equal to the sum of every other digit in a list. For example, if the list is [0,1,2,3,4,5], the function should equal 5+3+1. How could I do this? My knowledge of Python does not extend much farther than while and for loops. Thanks. </p>

<pre><code>&gt;&gt;&gt; arr = [0,1,2,3,4,5]
&gt;&gt;&gt; sum([x for idx, x in enumerate(arr) if idx%2 != 0])
9
</code></pre>

<p>This is just a list comprehension that only includes elements in <code>arr</code> that have an odd index.</p>

<p>To illustrate in a traditional <code>for</code> loop:</p>

<pre><code>&gt;&gt;&gt; my_sum = 0
&gt;&gt;&gt; for idx, x in enumerate(arr):
...     if idx % 2 != 0:
...         my_sum += x
...         print("%d was odd, so %d was added. Current sum is %d" % (idx, x, my_sum))
...     else:
...         print("%d was even, so %d was not added. Current sum is %d" % (idx, x, my_sum))
... 
0 was even, so 0 was not added. Current sum is 0
1 was odd, so 1 was added. Current sum is 1
2 was even, so 2 was not added. Current sum is 1
3 was odd, so 3 was added. Current sum is 4
4 was even, so 4 was not added. Current sum is 4
5 was odd, so 5 was added. Current sum is 9
</code></pre>

python for-loop while-loop sum