An English dictionary definedefines the words append and extend as:
append: add (something) to the end of a written document.
extend: make larger. Enlarge or expand
With that knowledge, now let's understand
- The difference between
appendandextend
append:
- Appends any Python object as-is to the end of the list (i.e. as a lastthe last element in the list).
- The resulting list may be nested and contain heterogeneous elements (i.e. list, string, tuple, dictionary, set, etc.)
extend:
- Accepts any iterable as its argument and makes the list larger.
- The resulting list is always one dimensional-dimensional list (i.e. no nesting) and it may contain heterogeneous elements in it (e.g. characters, integers, float) as a result of applying
list(iterable).
- Similarity between
appendandextend
- Both takestake exactly one argument.
- Both modify the list in-place.
- As a result, both returns
None.
Example
lis = [1, 2, 3]
# 'extend' is equivalent to this
lis = lis + list(iterable)
# 'append' simply appends its argument as the last element to the list
# as long as the argument is a valid Python object
lislist.append(object)