Open In App

Python List extend() Method

Last Updated : 10 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Python
a = [1, 2, 3]
b = [4, 5]

# Using extend() to add elements of b to a
a.extend(b)

print(a)

Output
[1, 2, 3, 4, 5]

Explanation: The elements of list b are added to the end of list a. The original list a is modified and now contains [1, 2, 3, 4, 5].

Syntax of List extend() Method

list_name.extend(iterable)

Parameters:

  • list_name: The list that will be extended
  • iterable: Any iterable (list, set, tuple, etc.)

Returns:

  • Python List extend() returns none.

Using extend() with Different Iterables

The extend() method can work with various types of iterables such as: Lists, Tuples, Sets and Strings (each character will be added separately)

Example:

Python
# Using a tuple
a = [1, 2, 3]
b = (4, 5)
a.extend(b)
print(a) 

# Using a set
a = [1, 2, 3]
b = {4, 5}
a.extend(b)
print(a)  

# Using a string
a = ['a', 'b']
b = "cd"
a.extend(b)
print(a)  

Output
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
['a', 'b', 'c', 'd']

Also Read - Python List Methods

Similar Article on List extend:


Next Article

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy