How to use extend() Function in Python with Example?

The `extend()` function in Python is used to add multiple items from an iterable (like a list, tuple, or string) to the end of an existing list. It essentially extends the list by appending elements from the given iterable.

Syntax:

list.extend(iterable)

– `list`: The list that will be extended.
– `iterable`: The iterable whose items will be added to the list.

Example 1: Extending a List with Another List

# Initial list
fruits = ['apple', 'banana', 'cherry']
# List to extend
more_fruits = ['orange', 'mango', 'grapes']
# Extending the list
fruits.extend(more_fruits)
print(fruits)

Output:

['apple', 'banana', 'cherry', 'orange', 'mango', 'grapes']

Example 2: Extending a List with a Tuple

# Initial list
numbers = [1, 2, 3]
# Tuple to extend the list
more_numbers = (4, 5, 6)
# Extending the list
numbers.extend(more_numbers)
print(numbers)

Output:

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

Example 3: Extending a List with a String

# Initial list
letters = ['a', 'b', 'c']
# String to extend the list
more_letters = "def"
# Extending the list
letters.extend(more_letters)
print(letters)

Output:

['a', 'b', 'c', 'd', 'e', 'f']

In the last example, notice that the string `”def”` is treated as an iterable of characters, so each character is added separately to the list.