Home >Backend Development >Python Tutorial >Python Lists: When to Use `append()` vs. `extend()`?

Python Lists: When to Use `append()` vs. `extend()`?

Susan Sarandon
Susan SarandonOriginal
2024-12-25 15:40:14904browse

Python Lists: When to Use `append()` vs. `extend()`?

Understanding the Nuances of Python's List Methods: append vs. extend

In Python, the list data structure is a versatile tool, and its methods provide various ways to manipulate its contents. Two commonly used methods are append() and extend(), but their distinct functionalities make them suitable for different scenarios.

append() vs. extend(): Key Differences

The primary difference between append() and extend() lies in the nature of the objects they add to a list:

  • append(): Accepts a single argument, which can be any object, and appends it to the end of the list.
  • extend(): Accepts an iterable (e.g., a list, tuple, range) and appends its elements one by one to the end of the list.

Practical Examples

To illustrate the distinction, consider the following code:

>>> x = [1, 2, 3]
>>> x.append([4, 5])
>>> print(x)
[1, 2, 3, [4, 5]]

In this case, the append() method treats [4, 5] as a single object and appends it to the end of the list, resulting in a nested list.

In contrast:

>>> x = [1, 2, 3]
>>> x.extend([4, 5])
>>> print(x)
[1, 2, 3, 4, 5]

Here, the extend() method iterates through the list [4, 5] and appends its elements individually to the end of the list. As a result, the output is a flat list containing the elements from both the original and the iterable.

Choosing the Right Method

The choice between append() and extend() depends on the specific requirements of the task:

  • Use append() to add a single complex object (e.g., a nested list, dictionary) to the end of a list.
  • Use extend() to append multiple simple objects (e.g., numbers, strings) from an iterable to the end of a list.

The above is the detailed content of Python Lists: When to Use `append()` vs. `extend()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn