names.append("Akira") # Mutation of existing list
names = names + ["Akira"] # New list is created and assigned to names
If the instructions don’t stipulate whether the existing list should be modified (mutated) OR a new list should be created, then either approach is acceptable. In either case, the end result will be that the variable names
will point to the list ["Maria", "Rohan", "Valentina", "Akira"]
However, appending and concatenating (using the +
operator) aren’t the same, and are indeed different.
Appending to a list modifies/mutates the existing list, whereas concatenating creates a new list.
Consider the following examples to illustrate the difference:
x = [1, 2, 3]
y = x # Doesn't copy or create a new list.
# Both variables hold reference to same memory location.
# Both variables point to same list.
print(x) # [1, 2, 3]
print(y) # [1, 2, 3]
y.append(4)
# append modifies/mutates existing list.
# Since both variables point to same list, so mutation is seen by both variables.
# We appended to y, but x points to the same list so it is also mutated/modified
print(x) # [1, 2, 3, 4]
print(y) # [1, 2, 3, 4]
y = y + [5]
# New list is created and assigned to y.
# Now, x and y point to different lists.
print(x) # [1, 2, 3, 4]
print(y) # [1, 2, 3, 4, 5]
# Now, any mutation to the x list will not be seen by y,
# and any mutation to the y list will not be seen by x.
Appending modifies/mutates the existing list, whereas concatenation creates a new list.
The +=
operator is a bit different. If used on mutable data types, it is NOT shorthand for concatenation.
If we are dealing with immutable data types such as strings or numbers, then:
a = "Hello"
b = a
print(a) # "Hello"
print(b) # "Hello"
b += " World"
# b holds a string which is an immutable data type,
# so b += " World" is equivalent to b = b + " World"
print(a) # "Hello"
print(b) # "Hello World"
a = 3
b = a
print(a) # 3
print(b) # 3
b += 5
# b holds an integer which is an immutable data type,
# so b += 5 is equivalent to b = b + 5
print(a) # 3
print(b) # 8
When the +=
operator is used on lists (mutable data type), then things are different:
a = [1, 2, 3]
b = a
b += [100, 200]
# Since b is a list(mutable), so += mutates the list.
# It is NOT equivalent to b = b + [100, 200]
# Using += mutates the existing list.
# It can be thought of as extending the existing list.
print(a) # [1, 2, 3, 100, 200]
print(b) # [1, 2, 3, 100, 200]
# The += operator extends (mutates) the existing list
# i.e. it extends the list by appending all the items in the iterable.
# No new list is created.
For more discussion about the use of +=
operator on lists, see: