newbie question
Gary Herron
gherron at islandtraining.com
Fri Apr 1 23:14:57 CEST 2011
On 04/01/2011 12:52 PM, Karl wrote:
>
> Hello,
>
>
> one beginner question:
>
>
> aList = [0, 1, 2, 3, 4]
>
> bList = [2*i for i in aList]
>
> sum = 0
>
> for j in bList:
>
> sum = sum + bList[j]
>
Your j is already an element of bList. You don't need to index bList
again. Instead do
for b in bList:
sum = sum+b
> 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, ...
>
No, it's not a control variable, it's the actual elements of the list.
If you want a control variable as an index you can do
for j in range(len(bList)):
sum = sum + bList[j]
But that is less efficient
>
> Thanks!
>
>
> Karl
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110401/ff0eeaf1/attachment.html>
More information about the Python-list
mailing list