Nothing Special   »   [go: up one dir, main page]

Open In App

Python List extend() Method

Last Updated : 10 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

three90RightbarBannerImg