+ 6
[Open Discussion] Using or Not Using The Inplace Operators?
The difference of using inplace operator or not using it inside a function and its effect on multiple calls! I have noticed a strange but interesting behaviour of inplace operators. (Please see the attached code.) https://code.sololearn.com/cwTc0x7V7uBi/?ref=app Did you know that there is difference between when you use inplace operators VS you don't in multiplefunction calls? Please share your thoughts and tell me more about this if you know something useful about it. 🙏❤
2 Réponses
+ 5
Hi! It’s a bit tricky to use mutable objects, like lists. When possible, its better to use immutable objects like tuples.
A global variable of a mutable object that’s used as argument in a function, is not copied to the functions parameter, but assigned. And therefore it’s not local, but will be pointed to the same object as the global variabel does:
>>> def func(lst: list) -> list:
>>> # Change global variable via lst!
>>> lst += [3] # In-place.
>>> # Variable lst became local!
>>> lst = lst + [4] # Not in-place.
>>> return lst # Return local variable.
>>>
>>> my_list = [1, 2] # Create list.
>>>
>>> # Print the value from the functions local variable lst.
>>> print(func(my_list))
[1, 2, 3, 4]
>>>
>>> # The global my_list is changed from inside the function! (Not [1, 2] anymore.)
>>> print(my_list)
my_list = [1, 2, 3]
You can always use id(obj) to see a objects unique id number. With in-place operations the id number is still the same before and after the operation. Oherwise it will be changed.