Published on

What is the `extend` Method in Python?

Authors
  • avatar
    Name
    hwahyeon
    Twitter

Detailed Explanation of the extend Method

  • The extend method adds each element of an iterable object to an existing list.
  • It modifies the original list directly and does not create a new list.

Usage

list_name.extend(iterable_object)
  • Iterable object: This includes lists, tuples, strings, sets, and dictionaries. (Any object that can be iterated over with a for loop.)

Examples and How It Works

Extending with a List

fruits = ['apple', 'banana']
fruits.extend(['cherry', 'date'])
print(fruits)  # Output: ['apple', 'banana', 'cherry', 'date']

Each element of the list ['cherry', 'date'] is added to fruits.

Extending with a String

letters = ['x', 'y']
letters.extend('abc')
print(letters)  # Output: ['x', 'y', 'a', 'b', 'c']

A string is treated as an iterable, and each character is added to the list.

Extending with a Tuple

numbers = [1, 2]
numbers.extend((3, 4))
print(numbers)  # Output: [1, 2, 3, 4]

Each element of the tuple (3, 4) is added to numbers.

Extending with a Set

eg = [1, 2]
eg.extend({3, 4})
print(eg)  # Output: [1, 2, 3, 4]

Elements of a set are added, but since sets are unordered, the order of added elements is not guaranteed.

Extending with a Dictionary

eg = ['a', 'b']
eg.extend({'x': 1, 'y': 2})
print(eg)  # Output: ['a', 'b', 'x', 'y']

Only the keys of the dictionary are added to the list.

Only iterable objects are allowed

eg = ['a', 'b']
eg.extend(5)  # Raises TypeError: 'int' object is not iterable

Non-iterable objects like integers cannot be used as an argument for extend.

Modifies the original list

eg = ['a', 'b']
result = eg.extend(['c', 'd'])
print(result)  # Output: None
print(eg)      # Output: ['a', 'b', 'c', 'd']

The extend method directly modifies the original list and does not return a new list.

Difference Between append and extend

The append method adds an object as a single element, while extend adds each element of an iterable individually.

Using append

eg = ['a', 'b']
eg.append(['c', 'd'])
print(eg)  # Output: ['a', 'b', ['c', 'd']]

The list ['c', 'd'] is added as a single element.

Using extend

eg = ['a', 'b']
eg.extend(['c', 'd'])
print(eg)  # Output: ['a', 'b', 'c', 'd']

Each element of ['c', 'd'] is added individually.