In Python, extend() method is used to add items from one list to the end of another list. This method modifies the original list by appending all items from the given iterable.
Using extend() method is easy and efficient way to merge two lists or add multiple elements at once.
Let’s look at a simple example of the extend() method.
a=[1,2,3]b=[4,5]# Using extend() to add elements of b to aa.extend(b)print(a)
[1, 2, 3, 4, 5]
Explanation:The elements oflist bare added to the end of list a. The original list ais modified and now contains [1, 2, 3, 4, 5].
Syntax of List extend() Methodlist_name.extend(iterable)Parameters:list_name: The list that will be extendediterable: Any iterable (list, set, tuple, etc.)Returns:Python List extend() returnsnone.
list_name.extend(iterable)
Parameters:
Returns:
The extend() method can work with various types of iterables such as:Lists,Tuples,Sets andStrings (each character will be added separately)
Example:
# Using a tuplea=[1,2,3]b=(4,5)a.extend(b)print(a)# Using a seta=[1,2,3]b={4,5}a.extend(b)print(a)# Using a stringa=['a','b']b="cd"a.extend(b)print(a)
[1, 2, 3, 4, 5][1, 2, 3, 4, 5]['a', 'b', 'c', 'd']
Also Read -Python List Methods
Similar Article on List extend:
A
Python Introduction
Input and Output in Python
Python Variables
Python Operators
Python Keywords
Python Data Types
Conditional Statements in Python
Loops in Python - For, While and Nested Loops
Python Functions
Recursion in Python
Python Lambda Functions
Python String
Python Lists
Python Tuples
Python Dictionary
Python Sets
Python Arrays
List Comprehension in Python
Python OOP Concepts
Python Exception Handling
File Handling in Python
Python Database Tutorial
Python MongoDB Tutorial
Python MySQL
Python Packages
Python Modules
Python DSA Libraries
List of Python GUI Library and Packages
NumPy Tutorial - Python Library
Pandas Tutorial
Matplotlib Tutorial
Python Seaborn Tutorial
StatsModel Library - Tutorial
Learning Model Building in Scikit-learn
TensorFlow Tutorial
PyTorch Tutorial
Flask Tutorial
Django Tutorial | Learn Django Framework
Django ORM - Inserting, Updating & Deleting Data
Templating With Jinja2 in Flask
Django Templates
Python | Build a REST API using Flask
How to Create a basic API using Django Rest Framework ?
Python Quiz
Python Coding Practice
Python Interview Questions and Answers