Skip to content Skip to sidebar Skip to footer

Python Variable Contents Changed By Function When No Change Is Intended

Here is a sample of code where a function is run repeatedly with new information for most of the input variables except one, good_ens. The input variable good_ens that should neve

Solution 1:

When you call doFile try this instead:

doFile(inputFile, outputFile, list(good_ens), 'CF', l)

I think of it this way: A list is a thing which points to the value of each element within the list. When you pass a list into a function, the thing that does the pointing gets copied, but the values of the things pointed to do not get copied.

doing list(good_ens) actually makes copies in memory of the elements of the list, and will keep the original values from getting changed. See below:

>>>defchange_list(the_list):...    the_list[0] = 77...return...>>>a=[0,1,2,3,4]>>>change_list(a)>>>a
[77, 1, 2, 3, 4]
>>>>>>a=[0,1,2,3,4]>>>change_list(list(a))>>>a
[0, 1, 2, 3, 4]

EDIT: The reasoning for this is that, as the other answers have indicated, list is a mutable data type in python. Mutable data types can be changed, whereas immutable data types cannot be changed but rather return new objects when attempting to update.

Solution 2:

In python, lists are mutable.

>>>a = [1,2,3]>>>deffun(d):... d.append(55)...>>>a
[1, 2, 3]
>>>fun(a)>>>a
[1, 2, 3, 55]
>>>fun(a[:])>>>a
[1, 2, 3, 55]
>>>fun(a)>>>a
[1, 2, 3, 55, 55]

If you want them to be immutable consider using a tuple.

Solution 3:

The other answers cover the idea that lists are mutable. Below is a possible refactoring that gets around this issue in what I think is a sensible way.

defdoFile(infileName, outfileName, goodens, timetype, flen):
    # ...
    min_ens, max_ens = goodens

    if max_ens < 0:
        max_ens = flen

    nens = max_ens - min_ens
    # ...

This way, you can still call the function as you have been, your variables within the function are named more aptly, and you never mutate the provided list object.

Post a Comment for "Python Variable Contents Changed By Function When No Change Is Intended"