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]
Hamed Salimian
  • 791
  • 2
  • 11
  • 28
  • Also: https://stackoverflow.com/questions/10262920/understanding-pythons-call-by-object-style-of-passing-function-arguments?noredirect=1&lq=1 – xnx Apr 21 '18 at 06: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 – Hamed Salimian Apr 21 '18 at 06:25
  • Python does neither pass by reference nor pass by value. It uses a ["call by sharing"](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing) evaluation strategy, sometimes called "call by object". I suggest you read the following: https://nedbatchelder.com/text/names.html – juanpa.arrivillaga Apr 21 '18 at 06:30
  • 1
    "I have no assignment here." -- `my_list1 = [6,6,6]` -- really? – user202729 Apr 21 '18 at 06:42
  • I mean assigning my list to another list dude! Something like b = a – Hamed Salimian Apr 21 '18 at 07:04
  • Right, dude, that works exactly the same. You don't assign to an object, i.e. it doesn't make sense to say "assign a list to another list", you assign to *variables*. `a = b` works *exactly* the same as `a = [6,6,6]` – juanpa.arrivillaga Apr 22 '18 at 02:13

0 Answers0