See my code in python 3.4. I can get around it fine. It bugs me a little. I'm guessing it's something to do with foo2 resetting a rather than treating it as list 1.
def foo1(a):
a.append(3) ### add element 3 to end of list
return()
def foo2(a):
a=a+[3] #### add element 3 to end of list
return()
list1=[1,2]
foo1(list1)
print(list1) ### shows [1,2,3]
list1=[1,2]
foo2(list1)
print(list1) #### shows [1,2]
3 Answers 3
In foo2
you do not mutate the original list referred to by a - instead, you create a new list from list1
and [3]
, and bind the result which is a new list to the local name a
. So list1
is not changed at all.
There is a difference between append and +=
>>> a = []
>>> id(a)
11814312
>>> a.append("hello")
>>> id(a)
11814312
>>> b = []
>>> id(b)
11828720
>>> c = b + ["hello"]
>>> id(c)
11833752
>>> b += ["hello"]
>>> id(b)
11828720
As you can see, append and += have the same result; they add the item to the list, without producing a new list. Using + adds the two lists and produces a new list.
In the first example, you're using a method that modifies a
in-place. In the second example, you're making a new a
that replaces the old a
but without modifying the old a
- that's usually what happens when you use the =
to assign a new value. One exception is when you use slicing notation on the left-hand side: a[:] = a + [3]
would work as your first example did.
-
Thank you - going to try the slicing notationShed– Shed05/23/2015 15:05:04Commented May 23, 2015 at 15:05
return()
if you do not return anything, and return is not a function. Instead you return an empty tuple - which certainly is not what you want.