简体   繁体   中英

Copy a variable in python (jupyter) / Use different functions with same variables

I wrote a small Programm in python but it don't work like expected.

Here's the code:

puzzle = [8, 7, 5, 4, 1, 2, 3, 0, 6]
def count(p):
        p[0] += 1
        return p
def main(p):
    print(p)
    l = count(p)
    print(l)
    print(p)

b1 = main(puzzle)

I expect that print(p) will be different from print(l), but the result of both is the same, it's the result that print(l) should have. But p did change also, however I would need it to be unchanged… Is this a special python behavior? Is there something I missed? I also tried to change the variable names in the functions, but that didn't help. I restarted the Compiler, but that didn't help either.

Is there a solution to store a function output and than call the function again without let the function change the given parameters? So that l will be the result after the calculation and p will stay the value before?

Kind Regards, Joh.

You are passing a List parameter. Parameter passing is Call-by-Object. Since a List is a mutable object in this situation it is similar to pass by reference and changes to your List object will persist. If you were passing an immutable, such as an Integer or String, it would be akin to pass by copy/value, and changes would not persist. Eg:

def s2asdf(s):
    s = "asdf"

s = "hello world"
s2asdf(s)
print s

... results in:

$ python example.py
hello world

The reason for this is because Python passes function parameters by reference. When you call the count function it allows the function to modify the list inside the function and the changes will be applied to the original object.

If you want to have the function not modify the list but instead return a different list, you will have to make a copy of the list either by passing a copy to the function or make a copy inside the function itself. There are many ways to copy a list in Python, but I like to use the list() function to do it.

This should fix your problem:

puzzle = [8, 7, 5, 4, 1, 2, 3, 0, 6]
def count(p):
    new_list = list(p)  # copy values of p to new_list
    new_list[0] += 1
    return new_list

def main(p):
    print(p)
    l = count(p)
    print(l)  # l is the new_list returned from count
    print(p)  # p stays the original value

b1 = main(puzzle)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM