0

I have a function similar to the following:

def getCost(list):
  cost = 0
  for item in list:
    cost += item
  return cost

and I call it as so:

cost = getCost([1, 2, 3, 4])

This is GREATLY simplified but it illustrates what is going on. No matter what I do, cost always ends up == 0. If I change the value of cost in the function to say 12, then 12 is returned. If I debug and look at the value of cost prior to the return, cost == 10

It looks like it is always returning the defined number for cost, and completely disregarding any modifications to it. Can anyone tell me what would cause this?

4
  • 2
    Code works for me (note that you shouldn't name a variable list). Commented Oct 25, 2010 at 22:59
  • There's something missing. When I tried the sample, cost == 10 after the call. Commented Oct 25, 2010 at 23:00
  • 3
    I'm afraid you'll need to post more code... the method defined above (literally cut and paste into python 2.6 and 3.1 and got expected behavior) Commented Oct 25, 2010 at 23:01
  • 1
    Show code that you have run yourself and that demonstrates your problem. Commented Oct 26, 2010 at 2:17

1 Answer 1

2

This should solve all of your problems (if summing the list items in cost is indeed what you're trying to do:

def getCost(costlist):
    return sum(costlist)

It accomplishes the exact same things and is guaranteed to work. It's also much more simple than using a loop and an accumulator.

Sign up to request clarification or add additional context in comments.

4 Comments

Or even simply: getCost = sum
I just don't want to break all of his code that refers to getCost().
You can assign functions like that in Python, and still call getCost() (it will then do exactly the same thing as sum()).
Oh, I see. Learn something new about Python every day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.