What is the difference between Python's list methods append and extend?
append()
adds an entire object at the end of the list, keeping its structure, while extend()
flattens the added iterable, appending its individual elements.
Using append()
"as is":
Using extend()
for seamless integration:
In terms of efficiency, append()
is a O(1)
operation, consistently fast no matter the list size. However, extend()
operates at O(k)
complexity where k is the length of the iterable. Both processes tweak the original list directly and do not create a new one.
When to use append()
versus extend()
append()
for individual elements or nested lists
When you have just a single object or a nested list to add to your list, append()
is your friend:
This approach is particularly helpful when you need to maintain relationships among data points or handle hierarchical data.
extend()
for merging iterables
Plan to merge a list with another iterable (list, tuple, set)? Use extend()
. It is more efficient compared to manually appending each item via a loop:
But watch out! extend()
can be more performance-intensive than only adding a single item with append()
.
Coding with clarity: append()
vs extend()
Selecting the right method makes your Python code more legible and aligns with the intent of your script. extend()
is prone to unpacking the element leading to unexpected data structures when adding a single non-iterable element, while using append()
to add multiple items would instead result in a nested list.
Compatibility with +=
operator
The +=
operator complements extend()
nicely and can be used for the same purpose with a cleaner syntax:
However, this may conceal the code's intention unlike .extend()
, which clearly states it.
Beware: Extend with a string
Remember that extend()
will treat a string as an iterable of characters:
This can lead to unexpected results if you intended the whole string as a single element.
Type Safety and Consistency
While append()
is more forgiving and can take any object, with extend()
, as each element of the iterable is added individually, make sure all the elements are compatible with your list's intended data type.
Was this article helpful?