Modify parameter as a side-effect in python

function, parameter-passing, python

Solution

You can't do this directly since integer and floating-point types are immutable in Python.

You could wrap `guess` into a mutable structure of some sort (e.g. a list or a custom class), but that would get very ugly very quickly.

P.S. I personally really like the explicit nature of `guess = improve_guess(guess, x)` since it leaves no doubt as to what exactly is being modified. I don't even need to know anything about `improve_guess()` to figure that out.

Problem

Possible Duplicate: Python: How do I pass a variable by reference? I'm trying to write a function that modifies one of the passed parameters. Here's the current code: ``` def improve_guess(guess, num): return (guess + (num/guess)) / 2 x = 4.0 guess = 2.0 guess = improve_guess(guess, x) ``` However, I want to write the code in such a way that I don't have to do the final assignment. That way, I can just call: ``` improve_guess(guess,x) ``` and get the new value in guess. (I intentionally didn't mention passing-by-reference because during my net-searching, I found a lot of academic discussion about the topic but no clean way of doing this. I don't really want to use globals or encapsulation in a list for this.)

Original source

Related problems