-2

I'm confused about the following 3 codes.

1.The first one is intuitive for me util I saw (B):

(A)

def change (mylist):
    mylist[0] = 33
    mylist[1] = 44
    mylist[2] = 55
    print("inside the function",mylist)

alist = [10,20,30]
change(alist)
print("outside the function",alist)

the output is:

inside the function [33, 44, 55]

outside the function [33, 44, 55]

2.As I saw the (B), I have trouble telling the difference of (A) and (B).

(B)

def change2 (mylist):
    mylist = [33,44,55]
    print("inside the funcion",mylist)

blist = [10,20,30]
change2(blist)
print("outside the funcion",blist)

the output is:

inside the function [33, 44, 55]

outside the function [10, 20, 30]

3.then, the third one is (C), and I can't figure out why "a" can't be changed to 5.

(C)

def change3(mylist,number):
    mylist[0] = 33
    mylist[1] = 44
    mylist[2] = 55
    number = 5
    print("inside the function",mylist,number)

clist = [10,20,30]
a = 50
change3(clist,a)
print("outside the function",clist,a)

the output is:

inside the function [33, 44, 55] 5

outside the function [33, 44, 55] 50

I know they might be have something with mutable or immutable concept, but I don't know the clear concept behind the three codes. Could someone explain them? thank you.

1 Answers1

0

You need to return the variable you modify inside the function for it to reflect in the outer values

Eg :

def change3(mylist,number):
    mylist[0] = 33
    mylist[1] = 44
    mylist[2] = 55
    number = 5

    return mylist, number

clist = [10, 20, 30]
a = 50
output = change3(clist, a)
print("outside the function", output)

Same for the all the cases you have mentioned.Since you have not returned,nothing is changing in the print which is outside the function and youre getting the unmodified values.

Abhishek Kulkarni
  • 1,747
  • 1
  • 6
  • 8