Python Reference ยท Lists, Tuples and Ranges
Python list.extend() method
Reference for Python list.extend(): append every item of an iterable to a list in place, how it differs from append() and +, and what happens with strings.
The extend() method adds every item from an iterable to the end of a list, one by one. It works in place and returns None. The iterable can be another list, a tuple, a set, a string, a range, a generator, a dictionary or anything else you can loop over.
Compare it with append(): append(x) adds x itself as a single element, while extend(x) adds the elements that x produces.
nums = [1, 2] nums.extend([3, 4]) print(nums) # [1, 2, 3, 4]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
list.extend(iterable)
| Name | Description |
|---|---|
iterable |
Any iterable object. Each item it yields is appended in order. |
Return value: None. The list is changed in place.
Raises: TypeError if the argument is not iterable (for example an integer).
Usage notes
- Mutates the list. Everyone holding a reference sees the new items. Do not write
a = a.extend(b), which setsatoNone. - Strings are iterables.
items.extend("abc")adds"a","b","c". To add the whole string, useappend("abc"). - Dictionaries give keys. Use
.values()or.items()for the other parts. +=is equivalent.a += bcallsextendunder the hood, so it also mutates in place and accepts any iterable.a = a + bbuilds a new list and accepts only another list.- Self-extension is safe.
s.extend(s)doubles the list; Python copies the items first. - Shallow. The new items are the same objects, not copies, as with every list operation.
- Performance. Amortized O(k) for k new items, much faster than calling
append()in a Python loop. Preferextend()over repeated+in loops, which creates a new list every time. - Insert in the middle with a slice assignment:
items[2:2] = more.
Related
list.append(),list.insert(),list.copy(),itertools.chain,list- Lessons: Lists, List methods, Unpacking