A small problem with python passing by reference

when I first learned python , I came across the following code. I thought about it according to the running result, and I don"t know whether it is correct or not.

version is python3.6

the code is as follows:

def g(p):
    z = p.pop(0)
    p.extend(z)
    return p

y = ["h", "i", "j"]
g(y).extend(g(y[:])) 

print(y) -sharp -> ["i", "j", "h", "j", "h", "i"]

personal understanding is as follows:

  1. first run g (y) . Since the function is passed by reference (I don"t know whether this expression is correct or not), the function is modified directly on y , and y becomes ["code," jacks,"h" ].
  2. now run the following .extend (g (y [:]) . First, copy a copy of y , and y remains unchanged at this time, and then perform the g (y [:]) operation, which changes y [:] to ["jacks," hashes,"i"] .
  3. finally, the extend () operation is performed, and y and y [:] are merged, and the final result is ["code >", "jacks," hashes, "jacks," hacks,"i"] .

I don"t know if the above understanding is wrong. I would like to ask the elder to give me some advice. I would appreciate it!

at the same time, I just thought of another question when I was writing a question:

Why can"t I run the g (y [:]) section first? If you run this section first, the final result should be ["ifinished," jacked, "hacked," ified, "jaded," h"] . However, the answer given by the interpreter is still above, so the doubts about this question can be summarized as follows:

if there is a.extend (b) , then whether to run a first or b first, why?

the question has been updated, and I hope that my predecessors can answer it. I would appreciate it!

Oct.23,2021

your understanding is correct.

< hr >
Why can't you run the g (y [:]) section first?

this part doesn't understand what it means

< hr >

a.extend (b) must evaluate a first, because the associativity of the . operator is from left to right, so when parsing this expression, evaluate a first, and then calculate extend, to find that this is a function call, and then calculate the parameter of the function

.
Menu