list.extend()
Python · Lists
Theory
.extend(iterable) loops over another iterable and appends each of its items to the end of the list, in place. sales = [100, 250] then sales.extend([300, 400]) gives [100, 250, 300, 400]. It accepts any iterable: a list, tuple, set, range or even a string, which is a common surprise because a string is iterated character by character, so nums.extend('ab') adds 'a' and 'b' separately.
The difference from append() is the key thing to learn. append() adds its argument as one single element, so appending [300, 400] gives a nested list of length 3; extend() unpacks it, giving length 4. sales += [300, 400] does the same in-place extend. In contrast, sales + [300, 400] builds a brand-new list and leaves the original unchanged. extend() returns None, and costs O(k) where k is the number of items added.
Why we use it
Combining batches of data is very common: rows from several files, pages of API results, results from several loops. extend() merges them into one flat list without writing a loop yourself.
When to use it
Use extend() (or +=) to add all items of another iterable to an existing list. Use append() to add one item, even if it is a list you want nested. Use a + b when you need a new combined list and must keep both originals.
How it works
- Call sales.extend([300, 400])
- Get an iterator over the argument
- Take the next item from it
- Append that single item to the end of sales
- More items in the iterable? Yes: Take the next one. No: Return None.
- print(sales) shows [100, 250, 300, 400]
Syntax
list.extend(iterable)Example
sales = [100, 250]
sales.extend([300, 400])
print(sales)Key points
- Unlike append(), it adds each item individually, not the whole iterable as one
- Equivalent to list += iterable
- Works with any iterable: tuple, set, range, string
- extend('ab') adds 'a' and 'b' separately
- Returns None; the list is modified in place