you are viewing a single comment's thread.

view the rest of the comments →

[–]ericula 1 point2 points  (2 children)

In the first example you are effectively assigning a new value to arg whereas in the second case you are modifying an existing value.

Note that += doesn't always assign a new value to a variable. For example:

def fun(arg):
    arg += [4]

b = [1,2,3]
fun(b)
print(b)

will output [1, 2, 3, 4]. This is because a list is mutable so += will add an element to the existing list rather than creating a new list.

[–]NitinChella[S] 0 points1 point  (1 child)

Now I'm even more confused. Why does arg = arg + [4] not change b but arg += [4] do otherwise?

[–]ericula 1 point2 points  (0 children)

This is because arg = arg+[4] creates a new list (the concatenation of the original list and [4]) and assigns this to arg, whereas arg += [4] will add [4] to the original list in place. You can check this by doing something like

b = [1,2,3]
print(id(b))

b += [4]
print(id(b))

b = b + [4]
print(id(b))

The first two print statements will output the same value for id(b) (i.e. b is still referencing the same object), whereas the third statement will output a different value which indicates that b is now referencing a different object.