List extend() Method in Python

Python List extend() Method

In Python, the extend() method is used to add all the elements from one list to the end of another list. It is a built-in method available for lists in Python.

Here's the basic syntax of the extend() method:

list_name.extend(iterable)
  • list_name: This is the name of the list to which you want to add elements.
  • iterable: This is an iterable (e.g., a list, tuple, string, etc.) containing elements that you want to add to the end of the list.

The extend() method modifies the original list in place by appending elements from the iterable to the end of the list.

Let's see some examples of using the extend() method:

Example 1:

# Create two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Extend list1 with elements from list2
list1.extend(list2)

print(list1)  # Output: [1, 2, 3, 4, 5, 6]

Example 2:

# Create a list
fruits = ['apple', 'banana']

# Create a tuple of new fruits
new_fruits = ('orange', 'grapes')

# Extend the fruits list with elements from the new_fruits tuple
fruits.extend(new_fruits)

print(fruits)  # Output: ['apple', 'banana', 'orange', 'grapes']

Example 3:

# Create a list
my_list = [1, 2, 3]

# Extend the list with elements from a string
my_list.extend('hello')

print(my_list)  # Output: [1, 2, 3, 'h', 'e', 'l', 'l', 'o']

As you can see, the extend() method is a convenient way to add multiple elements from an iterable to the end of a list, and it modifies the original list in place.