If i were to run this code:
def function(y): y.append('yes') return y example = list() function(example) print(example)
Why would it return ['yes'] even though i am not directly changing the variable 'example', and how could I modify the code so that 'example' is not effected by the function?
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
Use the * Operator in Python The * operator can unpack the given list into separate elements that can later be tackled as individual variables and passed as an argument to the function.
In Python, you can unpack list , tuple , dict (dictionary) and pass its elements to function as arguments by adding * to list or tuple and ** to dictionary when calling function.
Everything is a reference in Python. If you wish to avoid that behavior you would have to create a new copy of the original with list()
. If the list contains more references, you'd need to use deepcopy()
def modify(l): l.append('HI') return l def preserve(l): t = list(l) t.append('HI') return t example = list() modify(example) print(example) example = list() preserve(example) print(example)
outputs
['HI'] []
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With