Home > Backend Development > Python Tutorial > The difference between append and extend in Python

The difference between append and extend in Python

silencement
Release: 2019-05-25 15:45:02
Original
3546 people have browsed it

The difference between append and extend in Python

Look at the code first, and then explain the principle

The difference between append and extend in Python

Principle:

The two methods of Lists extend and append looks similar, but is actually completely different. extend accepts a parameter, which is always a list, and adds each element in this list to the original list.

Here there are 3 elements in the list ('a', 'b' and 'c'), and use another one with 3 elements ('d', 'e' and 'f') list is expanded so there are 6 elements in the new list.

Append, on the other hand, accepts a parameter, which can be of any data type, and is simply appended to the end of the list. Here the append method is called with a list parameter containing 3 elements.

The original list containing 3 elements now contains 4 elements. Why 4 elements? Because the last element just appended is itself a list. Lists can contain any type of data, including other lists. This may or may not be the result you want. If your intention is to extend, don't use append.

The above is the detailed content of The difference between append and extend in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template