Home >Backend Development >Python Tutorial >Append() vs. Extend(): How Do These Python List Methods Differ?

Append() vs. Extend(): How Do These Python List Methods Differ?

Susan Sarandon
Susan SarandonOriginal
2024-12-19 00:37:11273browse

Append() vs. Extend(): How Do These Python List Methods Differ?

Append vs Extend: Unveiling the Differences in Python List Manipulation

In Python, lists serve as powerful data structures that can be extended and modified using various methods. Two commonly used methods with distinct functionalities are append() and extend().

Key Distinction: Singular vs Multiple Objects

The fundamental difference between these methods lies in the type of elements they add to a list:

  • append(): Appends a single object to the end of the list.
  • extend(): Extends the list by iteratively adding multiple objects from a specified iterable object.

Practical Demonstration

Consider the following examples:

x = [1, 2, 3]
x.append([4, 5])
print(x)
# Output: [1, 2, 3, [4, 5]]

In this example, the .append() method adds a single object, the nested list [4, 5], to the end of the x list. As a result, the resulting list contains the original elements followed by the appended nested list.

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

In this case, the .extend() method iteratively adds each element (4 and 5) from the iterable [4, 5] to the end of the x list. The resulting list contains the original elements extended by the additional items.

Conclusion

Understanding the distinction between .append() and .extend() is crucial for effective list manipulation in Python. Remember that .append() appends a single object, while .extend() extends the list with multiple objects from an iterable, ensuring optimal code efficiency.

The above is the detailed content of Append() vs. Extend(): How Do These Python List Methods Differ?. 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