Problems with Python----function call values

Source: Internet
Author: User

ImportNumPy as NPdefBuild_chessboard (N): Chessboard=Np.zeros ((n,n))returnChessboarddefPrint_chessboard (chessboard): N=Len (chessboard) forRinchRange (N): forCinchRange (N):ifCHESSBOARD[R,C] = = 1:                Print('Q', end="")            Else:                Print('.', end="")        Print ()    Print ()#generate an empty 4x4 chessboard:Chessboard = Build_chessboard (4)Print(chessboard)#Place 4 non-attacking Queens in this boardchessboard[1,0] = 1chessboard[3,1] = 1Chessboard[0,2] = 1chessboard[2,3] = 1#pretty print the resulting boardPrint_chessboard (chessboard)defTest (CB): cb[0, 0]= 1Print_chessboard (CB) Chessboard= Build_chessboard (4) Print_chessboard (chessboard) test (Chessboard.copy ())#try Chessboard.copy () insteadPrint_chessboard (Chessboard)#oooops!defTest (b): b= B + 1Print(b) n= 1Print(n) test (n)Print(n)ImportCopydefTest (b): B.append (1)    Print(b) n= [1, 2, 3]Print(n) test (copy.copy (n) )Print(n) test (n)Print(n) a=[]copy.deepcopy (a)ImportCopy#copy makes a copy of the Outer-most object, but keeps the same references to the inner#object.A=[2,4,[6]]Print("before:a=", a) b=Copy.copy (a) b[0]+=1b[2][0]+=1Print("after:a="A"b="B"(using copy)")#Deepcopy also makes a copy of each contained element (recursively)A=[2,4,[6]]b=Copy.deepcopy (a) b[0]+=1b[2][0]+=1Print("after:a="A"b="B"(using deepcopy)")

To summarize: The function call can not change the original value (similar to the time the value is passed), but can change the original list (append). Deepcopy is safer than copy because no inner reference (copy, inner reference may cause inner layer values to be modified)

Problems with Python----function call values

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.