What is the difference between in-place changes and non-in-place variables in Python 3.6.4 functions?

Asked 2 years ago, Updated 2 years ago, 35 views

I'm trying to make the code comparable under the same conditions as possible, but no matter how many times I try, the list is rewritten in-place. Why?I would appreciate it if the answer was anything other than "You should use tuples instead of lists."

Also, since this is my first question post, I think there are some rude points, so it would be even more helpful if you could point that out.Thank you for your cooperation.

>>>lst,a=[0],0
>>def test1(lst):
    try:
        _=lst
        _[0] = 1
    except:
        pass
    return_
>>def test2(x):
    try:
        b = a
        b = 1
    except:
        pass
    return b
>> test1(lst)
[1]
>>>lst
[1] # I want it to remain 0 here.
>> test2(a)
1
>>a
0

python python3

2022-09-30 17:57

2 Answers

In the code in question, id(test1(lst)) and id(lst) are identical and refer to the same.
The code for the question should be as follows.

def test1(lst):
    try:
        _=lst.copy()
        _[0] = 1
    except:
        pass
    return_


2022-09-30 17:57

There is an explanation in Python's official FAQ, so you should read it first:

Simply supplement, when you create an object like a list, you create a single entity that stores the contents of the element, and when you argument or substitute a function for the object itself, you do not create a new entity, but a reference to point to it.

Therefore, when passing a list to a function argument, to prevent the function to which you pass from modifying the original list, instead of passing lst to the argument, you can pass lst[:] or lst.copy() to create a new list.Alternatively, you can create and pass a tuple that is an array that cannot be modified, such as tuple(lst) (in this case, the variable that receives the tuple will fail if it tries to change its contents).


2022-09-30 17:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.