List Methods
extend()
Append elements from an iterable to the end of the list.
list.extend(iterable)
list.extend() iterates over iterable and appends each element individually to the end of the list.
This is equivalent to iterating with a for loop and calling append() on each item, but implemented in optimized C.
Arguments
Parameters
| Name | Description |
|---|---|
| iterable | Any iterable object (list, tuple, set, string, or generator) whose items will be appended. |
Result
Returns
None, the list is extended in place.
Run it
Try it
Run it and change it
primary = ["red", "green"] secondary = ["yellow", "cyan"] primary.extend(secondary) print(primary)
Output
Press Run to see what it prints.Worth knowing
- Extending strings: If you pass a string to
extend(), it unpacks each individual character into the list:[].extend('cat')becomes['c', 'a', 't']. - In-place operator: The
+=operator on lists (e.g.list_a += list_b) callsextend()under the hood.