25

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?

S.Lott
  • 384,516
  • 81
  • 508
  • 779
Slinc
  • 251
  • 1
  • 3
  • 3
  • http://effbot.org/zone/default-values.htm describes a different but somewhat related issue. Reading that might help you understand what's going on. – Tyler Feb 23 '10 at 22:04
  • The other way to look at it: you CAN append to a list in a function, which is extremely useful. – Technophile Sep 14 '21 at 16:58

4 Answers4

49

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']
[]
Vinko Vrsalovic
  • 330,807
  • 53
  • 334
  • 373
  • 5
    You can also create a copy of any list with `myList[:]`, but keep in mind this is a "shallow copy" meaning that the nth element of the new list refers to the same object as the nth element of the old one. – Tyler Feb 23 '10 at 22:03
10

The easiest way to modify the code will be add the [:] to the function call.

def function(y):
    y.append('yes')
    return y



example = list()
function(example[:])
print(example)
Mike Kaufman
  • 101
  • 1
  • 2
9

"Why would it return ['yes']"

Because you modified the list, example.

"even though i am not directly changing the variable 'example'."

But you are, you provided the object named by the variable example to the function. The function modified the object using the object's append method.

As discussed elsewhere on SO, append does not create anything new. It modifies an object in place.

See Why does list.append evaluate to false?, Python append() vs. + operator on lists, why do these give different results?, Python lists append return value.

and how could I modify the code so that 'example' is not effected by the function?

What do you mean by that? If you don't want example to be updated by the function, don't pass it to the function.

If you want the function to create a new list, then write the function to create a new list.

Community
  • 1
  • 1
S.Lott
  • 384,516
  • 81
  • 508
  • 779
0

Its because you called the function before printing the list. If you print the list then call the function and then print the list again, you would get an empty list followed by the appended version. Its in the order of your code.

David Agabi
  • 43
  • 1
  • 8