# newbie question

eryksun () eryksun at gmail.com
Fri Apr 1 16:48:44 EDT 2011

```Regarding the format of your post, please use plain text only.

On Friday, April 1, 2011 3:52:24 PM UTC-4, Karl wrote:
>
> aList = [0, 1, 2, 3, 4]
> bList = [2*i for i in aList]
> sum = 0
> for j in bList:
>     sum = sum + bList[j]
>     print j
>
> 0
> 2
> 4
>
> IndexError: list index out of range
>
> Why is j in the second run 2 and not 1 in the for-loop?? I think
> j is a control variable with 0, 1, 2, 3, ...

The for loop yields the elements of bList, not their index (it's like a foreach statement in other languages). Here's the full printout:

In [1]: aList = [0, 1, 2, 3, 4]
In [2]: bList = [2*i for i in aList]
In [3]: for j in bList:
...:     print j

0
2
4
6
8

Since bList is 5 elements long, bList[6] is indeed "out of range". Here's a more direct way to accomplish this task:

In [4]: b_sum = sum(bList)
In [5]: b_sum
Out[5]: 20

Note that I'm not overwriting the name of the built-in function 'sum'. Try to avoid doing that. It's pretty simple to type the name in the interpreter and see if it's already bound to something you might want to keep around.

Here's one way to get the index in a loop:

In [6]: b_sum = 0
In [7]: for j, b in enumerate(bList):
...:     b_sum += b
...:     print j

0
1
2
3
4

In [9]: b_sum
Out[9]: 20

The enumerate function returns an iterable that's a tuple of the index and item. A for loop iterates over an iterable object such as a sequence.

```