0

Here are my test codes.

Test 1:

def set(object):
    object = [2,3]
a = [1,3]
set(a)
print a 

The output is [1,3]

Test 2:

def set(object):
    object[0] = 2
a = [1,3]
set(a)
print a

The output is [2,3]

For Test 2, I can know it well, because a is a list, which transfer reference in python. So when call set(object), object is a reference of a. Therefore a change into [2,3]. But for Test 1, I have not knew it well. I think the answer is [2,3], but the real answer is [1,3]. Can anyone tell me the two test case's differences?

cwfighter
  • 502
  • 1
  • 5
  • 20

1 Answers1

0

In the second test case, you are trying to mutate the existing list, so that will work.

But, in your first test, you are trying to assign a new list on variable a, but you are doing it inside function scope, rather you should return object and receive it in a.

>>> def set_value(a):
...     a=[2,3]
...     return a
...
>>> a=[1,3]
>>> a = set_value(a)
>>> a
[2, 3]
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57