FAQ: Creating and Modifying a List in Python - Growing a List: Append

Append is generally for adding a single extra element to a list. The operator += is generally (with some subtle differences) syntactic sugar for the list.extend() method instead which is used for adding multiple elements to the list.

Note the difference between append and += in that you cannot append the integer literal and it has to be a list (more generally it has to be iterable)-

lst = [0]
lst.append(1)  # this is fine
# lst += 2  # this would not work, int object is not iterable
lst += [2]  # acceptable because the list is iterable
# lst.extend(3)  # error, int obj not ierable
lst.extend((3, 4))  # tuple 3, 4 is iterable so we're good
print(lst)
Out: [0, 1, 2, 3, 4]

So, yes, there is a difference in how the code is interpreted (for .append, .extend and +=) but it’s not something you need to worry about all that much for the time being. As for subtle differences, there’s a SO question about this which goes into more detail (python2 rather than 3 so I’ve not checked if this has altered at all, probably not all that much)-

You could also create a list with + in the way you suggest but it’s not really very useful-

new_list = [] + [1, 2, 3]  # [] creates an empty list and + concatenates the two
# ... but why not just create a single new list?
new_list2 = [1, 2, 3]
new_list == new_list2  # equates to True

So there’s more than one way to perform the same action but aim for readability first and foremost.

1 Like