Home  >  Article  >  Backend Development  >  The difference between python append, extend and insert

The difference between python append, extend and insert

WBOY
WBOYOriginal
2016-12-05 13:27:121515browse

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‘]

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‘]

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‘]。

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!

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