how does a function changes the value of a variable outside its scope? Python

2024/10/5 16:19:55

i was coding this code and noticed something weird, after my function has been called on the variable, the value of the variable gets changed although its outside of the functions scope, how exactly is this happening?

def test(my_list):if 11 in my_list and sum(my_list) > 21:my_list.remove(11)my_list.append(1)return sum(my_list)ca = [11,11]
print(test(ca))
print(ca)

the above code results to:

12
[11, 1]
Answer

Because my_list is a list, a mutable object.

https://docs.python.org/3/faq/programming.html#why-did-changing-list-y-also-change-list-x

In other words:

  • If we have a mutable object (list, dict, set, etc.), we can use some specific operations to mutate it and all the variables that refer to it will see the change.

  • If we have an immutable object (str, int, tuple, etc.), all the variables that refer to it will always see the same value, but operations that transform that value into a new value always return a new object.

https://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference

3. By passing a mutable (changeable in-place) object:
>>>>>> def func2(a):
...     a[0] = 'new-value'     # 'a' references a mutable list
...     a[1] = a[1] + 1        # changes a shared object
...
>>> args = ['old-value', 99]
>>> func2(args)
>>> args
['new-value', 100]

You can change the content of a list, but not a list itself. For example:

>>> def test(my_mutable):
...  my_mutable = [1]
...  print(my_mutable)
... 
>>> my_mutable = [2]
>>> test(my_mutable)
[1]
>>> my_mutable
[2]

You can do the same with dict:

>>> ca = {11: 11, 12: 12}
>>> def test(my_dict):
...  if 11 in my_dict and sum(my_dict.values()) > 21:
...    del my_dict[11]
...    my_dict[1] = 1
...  return sum(my_dict.values())
... 
>>> test(ca)
13
>>> ca
{12: 12, 1: 1}
https://en.xdnf.cn/q/119673.html

Related Q&A

Python extracting element using bs4, very basic thing I think I dont understand

So Im using Beautiful Soup to try to get an element off of a page using the tag and class. Here is my code: import requests from bs4 import BeautifulSoup# Send a GET request to the webpage url = "…

Why Isnt my Gmail Account Bruteforcer Working? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 4 years ago.Improve…

Python: Split Start and End Date into All Days Between Start and End Date

Ive got data called Planned Leave which includes Start Date, End Date, User ID and Leave Type.I want to be able to create a new data-frame which shows all days between Start and End Date, per User ID.S…

Python and java AES/ECB/PKCS5 encryption

JAVA VERSION:public class EncryptUtil {public static String AESEncode(String encodeRules, String content) {try {KeyGenerator keygen = KeyGenerator.getInstance("AES");keygen.init(128, new Secu…

How to find the center point of this rectangle

I am trying to find the center point of the green rectangle which is behind the fish, but my approach is not working. Here is my code:#Finding contours (almost always finds those 2 retangles + some noi…

Simple Battleships game implementation in Python

Okay Im not sure how to develop another board with hidden spaces for the computers ships per-se, and have it test for hits. Again Im not even sure how Im going to test for hits on the board I have now.…

How to remove WindowsPath and parantheses from a string [duplicate]

This question already has an answer here:Reference - What does this regex mean?(1 answer)Closed 4 years ago.I need to remove WindowsPath( and some of the closing parentheses ) from a directory string.…

How to escape escape-characters

I have a string variable which is not printing properly, I guess because it contains escape characters. How to escape these escape-characters?>>> print "[p{Aa}\\P{InBasic_Latin}\r\t\n]&q…

Python Multiprocessing a large dataframe on Linux

As shown in the title, I have a big data frame (df) that needs to be processed row-wise, as df is big (6 GB), I want to utilize the multiprocessing package of python to speed it up, below is a toy exam…

How to pass more arguments through tkinter bind

How do I pass more arguments through tkinters bind method? for the example:tk = Tk() def moveShip(event,key):if event.keysym == Down and player1.selectedCoord[1] != 9:if key == place:player1.selectedC…