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:
- 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 ony
, andy
becomes["code," jacks,"h"
]. - now run the following
.extend (g (y [:])
. First, copy a copy ofy
, andy
remains unchanged at this time, and then perform theg (y [:])
operation, which changesy [:]
to["jacks," hashes,"i"]
. - finally, the
extend ()
operation is performed, andy
andy [:]
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!