A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-list-extend-method/ below:

Python List extend() Method - GeeksforGeeks

Python List extend() Method

Last Updated : 10 Dec, 2024

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)

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:

Returns:

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:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4