Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

passing list vs int in python important

in simple c++ analogy:
int,string,float aka immutables are passed by value hence can't change
list aka mutable passed by reference hence can change


Python passes references to objects. Inside your function you have an object -- You're free to mutate that object (if possible). However, integers are immutable. One workaround is to pass the integer in a container which can be mutated:

def change(x):
    x[0] = 3

x = [1]
change(x)
print x
This is ugly/clumsy at best, but you're not going to do any better in Python. The reason is because in Python, assignment (=) takes whatever object is the result of the right hand side and binds it to whatever is on the left hand side *(or passes it to the appropriate function).

Understanding this, we can see why there is no way to change the value of an immutable object inside a function -- you can't change any of its attributes because it's immutable, and you can't just assign the "variable" a new value because then you're actually creating a new object (which is distinct from the old one) and giving it the name that the old object had in the local namespace.

Usually the workaround is to simply return the object that you want:

def multiply_by_2(x):
    return 2*x

x = 1
x = multiply_by_2(x)
*In the first example case above, 3 actually gets passed to x.__setitem__.

Comment

PREVIOUS NEXT
Code Example
Python :: django updateview not saving 
Python :: pandas version for python 3.9 
Python :: travers a list 
Python :: python convert dataframe target to numbers 
Python :: bulet in jupyter notebook 
Python :: python sqlite select where 
Python :: dict keys in tcl 
Python :: generate pycryptodome salt 
Python :: cmd python script stay open 
Python :: Explaining async session in requests-html 
Python :: Python NumPy atleast_3d Function Example when inputs are high dimesion 
Python :: Python NumPy copyto function example copy elements from a source array to a destination array. 
Python :: python f strings 
Python :: Set changed size during iteration 
Python :: Python NumPy require Function Example with requirements attribute 
Python :: get text from heatmap 
Python :: fpdf latin-1 
Python :: pass dictionary to random forest regressor 
Python :: NumPy resize Example out of bound values [appending zeros] 
Python :: beaglebone install python 3.7 
Python :: URL to origin python 
Python :: how to separate data from two forms in django 
Python :: penggunaan clear di python 
Python :: python call c function 
Python :: How to Export Sql Server Result to Excel in Python 
Python :: fetch inbox mail python 
Python :: problème barbier semaphore python 
Python :: sklearn encoding pipelin 
Python :: how to wait 5 seconds in python 
Python :: clear notebook output 
ADD CONTENT
Topic
Content
Source link
Name
7+9 =