The difference between python append, extend and insert

WBOY
Release: 2016-12-05 13:27:12
Original
1615 people have browsed it

Recently, I was learning the Python language by myself, and I was confused by the append(), extend(), and insert() methods when I saw how to add more data to a list.

Append and extend both require only one parameter and are automatically added to the end of the array. If you need to add more than one, you can use array nesting, but append treats the nested array as an object,

extend is to add the contents of the nested array to the original array as multiple objects

As a novice with zero programming knowledge, I feel it is necessary to sort it out again:

1.append() method refers to adding a data item to the end of the list.

For example: add the "Gavin" item at the end of the students list.

>>> students = [‘Cleese‘ , ‘Palin‘ , ‘Jones‘ , ‘Idle‘]
>>> students.append(‘Gavin‘)
>>> print(students)
[‘Cleese‘, ‘Palin‘, ‘Jones‘, ‘Idle‘, ‘Gavin‘]

Copy after login

2. The extend() method refers to adding a data set at the end of the list.

For example: Based on Example 1, continue to add "Kavin", "Jack" and "Chapman" to the end of the students list. ​

>>> students = [‘Cleese‘ , ‘Palin‘ , ‘Jones‘ , ‘Idle‘]
>>> students.append(‘Gavin‘)
>>> print(students)
[‘Cleese‘, ‘Palin‘, ‘Jones‘, ‘Idle‘, ‘Gavin‘]
>>> students.extend([‘Kavin‘,‘Jack‘,‘Chapman‘])
>>> print(students)
[‘Cleese‘, ‘Palin‘, ‘Jones‘, ‘Idle‘, ‘Gavin‘, ‘Kavin‘, ‘Jack‘, ‘Chapman‘]

Copy after login

3. The insert() method refers to adding a data item in front of a specific position.

For example: Add "Gilliam" in front of "Palin" in the original list of students.

>>> students = [‘Cleese‘ , ‘Palin‘ , ‘Jones‘ , ‘Idle‘]
>>> students.insert(1, ‘Gilliam‘)
>>> print(students)
[‘Cleese‘, ‘Gilliam‘, ‘Palin‘, ‘Jones‘, ‘Idle‘]。

Copy after login

Since the data items are stacked from bottom to top, the first data number in the stack is 0 and the second data number is 1, so it is students.insert(1, ‘Gillam‘).

Thanks for reading, I hope it can help everyone, thank you for your support of this site!

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