0

I am new to python. I searched a lot but couldn't find the reason why this is happening. Could anyone please tell me the difference between these two?

My general question is when using a list in function is by reference and when is by value?

My test function is acting as call by reference and test2 is acting as call by value.

I know in python everything is an object, but with that, I couldn't understand the difference. tnx

def test(my_list):
    for i in range(len(my_list)):
        my_list[i] = 5


def test2(my_list1):
    my_list1 = [6, 6, 6]


a = [4, 4, 4]
print(a)
test(a)
print(a)
test2(a)
print(a)

output:

[4, 4, 4]
[5, 5, 5]
[5, 5, 5]
6
  • Also: stackoverflow.com/questions/10262920/… Commented Apr 21, 2018 at 6:20
  • @user202729 my question differs from them, because they have assigned the list to another variable which I know how that works, but I have no assignments here Commented Apr 21, 2018 at 6:25
  • Python does neither pass by reference nor pass by value. It uses a "call by sharing" evaluation strategy, sometimes called "call by object". I suggest you read the following: nedbatchelder.com/text/names.html Commented Apr 21, 2018 at 6:30
  • 1
    "I have no assignment here." -- my_list1 = [6,6,6] -- really? Commented Apr 21, 2018 at 6:42
  • I mean assigning my list to another list dude! Something like b = a Commented Apr 21, 2018 at 7:04

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.