What Is the extend() Method in Python?
The extend() method is a powerful built-in list function used to add multiple elements to the end of an existing list. Unlike append(), which inserts the entire object as a single item, extend() unpacks the iterable and adds each element individually.
This makes it ideal when merging lists, joining sequences, or updating your data dynamically without creating extra nested lists.
2. Purpose of extend() Method
The primary purpose of the extend() method is to merge the contents of any iterable into a list. Whether you’re working with lists, tuples, sets, strings, generators, or even dictionaries, the extend() method provides a clean and efficient way to grow your list. It is especially helpful when handling combined datasets, processing dynamic inputs, or when you simply want to avoid nested structures caused by append().
3. Syntax of extend() Function
list.extend(iterable)
This simple syntax makes extend() easy to use in everyday Python programming.
4. Parameter Description
| Parameter | Description |
|---|---|
| iterable | Any iterable (list, tuple, set, string, dictionary, generator, etc.) whose elements are added to the existing list. |
There are no additional arguments — len() is simple, clean, and incredibly efficient.
5. Python extend() – Practical Examples
The extend() method is one of the most flexible list operations in Python because it accepts any iterable. Here are clear, real-world-style examples that show exactly how it works with different data types.
Example 1: Extending a List with Another List
colors = ["red", "green"]
more_colors = ["blue", "yellow"]
colors.extend(more_colors)
print(colors)
#Output
['red', 'green', 'blue', 'yellow']
Explanation:
Each element from more_colors is added individually to the colors list, creating one combined list.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.