Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python passing list as argument

Tags:

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?

like image 944
Slinc Avatar asked Feb 23 '10 21:02

Slinc


People also ask

Can I pass a list as argument in Python?

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.

How do you pass a number and a list as an argument in Python?

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.

How do you pass a list of items in a Python 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.


1 Answers

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'] [] 
like image 194
Vinko Vrsalovic Avatar answered Sep 23 '22 04:09

Vinko Vrsalovic