1

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]
1
  • 2
    Unrelated to this: there is no reason to use 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. Commented May 20, 2015 at 21:29

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

1 Comment

Thank you - going to try the slicing notation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.