+ 1

Why is list(object) modified despite omitting global keyword inside function?

arr = [] x = 0 def test(): x = 1 arr.append(1) test() print(arr) """ If i assign arr = 10 then it doesnt affect outside but using method like append(1) has effect on it. Why does test function append 1 to list when i am not using global keyword (global list) but this doesnt affect x unless i use global keyword. Does that mean objects doesnt need to be explicitly be done something like global some_object. Plus isn't integer itself object in python? So why does omitting global works with list but not int. """ """ I have some basic concepts of pointers array and functions in c. is it somehow similar to array passed to function in C(we could perform operations like appending element to the array even inside function)

26th May 2023, 3:43 AM
Bishnu Chalise
Bishnu Chalise - avatar
3 Réponses
+ 1
The reason this happens is because inside the function you assign a value to "x" and not assinging any value to "arr". When you assign a value ("x = 1") a new variable in the current scope is created. In this example in the local scope for test(). So you have two variable with the same name in different scopes (local and global). When you use a variable without assignment ("arr.append(1)") the name of the variable is searched in the local scope, and if it is not found, then in the global scope. And if it is not found in the global scope, then the NameError("name ... is not defined") is thrown. There's a good thorough article on this topic: https://realpython.com/JUMP_LINK__&&__python__&&__JUMP_LINK-scope-legb-rule/
30th May 2023, 12:28 PM
Евгений
Евгений - avatar
+ 2
You said you know some C. Like arrays in C, Python lists are mutable and is passed by reference. So modifying it, even within a function closure, will modify the list. Objects like ints and strings are immutable, so they behave differently. That's also why you have to be careful when using lists as containers or parameters within functions. You might get unexpected results if the list gets mutated as the variables gets called further down the program execution.
26th May 2023, 4:06 AM
Bob_Li
Bob_Li - avatar
+ 1
Well one big difference there is that "arr = 10" just creates a new int named arr within the scope of the function, cause that's not valid array syntax. You can use arr[0] = 10 instead and it'll mutate as expected, but you'll also need to initialize the array to have a zero index first or you'll just get an out of bounds error.
26th May 2023, 4:48 AM
Orin Cook
Orin Cook - avatar