problem adding list values

andy andy at wild-flower.co.uk
Thu Dec 22 15:45:11 EST 2005


David M. Synck wrote:

>Hi all, 
>
>I am fairly new to Python and trying to figure out a syntax error
>concerning lists and iteration through the same. What I am trying to do is
>sum a list of float values and store the sum in a variable for use later.
>
>The relevant code looks like this -
>
>def getCredits():
>
>    """ This function asks the user to input any credits not shown on their bank statement
>
>    It returns the sum(converted to float) of the entered credits """
>
>    global credits
>    credlist = []
>    credits = 0.0
>    temp = 0.0
>    print "Now you need to enter any credits not shown on your bank statement \n"
>    print "Please enter a zero (0) once all credits have been entered \n"
>    raw_input("Hit 'Enter' to continue \n")
>    temp = float(raw_input("Please enter the first credit \n"))
>
>    while temp != 0:
>        credlist.append(temp)
>        temp = float(raw_input("Please enter the next credit \n"))
>       
>    i = 0
>    for i in credlist:
>        credits += credlist[i]
>        i = i + 1
>    
>    return credits
>
>And the syntax error I get is this - 
>
>Traceback (most recent call last):
>  File "./BankReconciler_Rev1.py", line 129, in ?
>    main()
>  File "./BankReconciler_Rev1.py", line 116, in main
>    getCredits()
>  File "./BankReconciler_Rev1.py", line 60, in getCredits
>    credits += credlist[i]
>TypeError: list indices must be integers
>
>
>If anyone can point me in the right direction, I would greatly appreciate
>it.
>
>Thanks in advance
>  
>
Your problem is here:

    i = 0 
    for i in credlist:	
        credits += credlist[i]
        i = i + 1

In the for loop, i is successively bound to each element in credlist
(which are floats) and you then try to index credlist with each element
in turn: you can't index lists with floats, so you get an error.

Try inserting a print command just before the credits expression, and
you'll see what I mean:

    i = 0 
    for i in credlist:	
	print i
        credits += credlist[i]
        i = i + 1


What you probably mean is:

credits = 0.0
for i in credlist:
credits += i

However, you should really use:

credits = sum(credlist)

It's far faster and more "pythonic".

NOTE: Although it may be easy to think of Python lists as arrays,
they're more than that. The Python for loop moves through a list,
binding (think assigning) the loop variable (in this case "i") to each
*element* of the list at a time on successive iterations, viz:

>>> for i in ["apples","oranges","grapes","pears","tomatoes"]:
... print i
apples
oranges
grapes
pears
tomatoes
>>>

Hope that helps ;-)

-andyj



More information about the Python-list mailing list