The difference between python append extend and insert

  • 2020-05-17 05:42:35
  • OfStack

Recently, when I was teaching myself Python, I was confused by the append (), extend (), insert () methods when I saw adding more data to the list.

Both append and extend need only one parameter and are automatically added to the end of the array. If more than one is needed, the array can be nested, but append takes the nested array as one object.

extend adds nested array contents as multiple objects to the original array

As the basis of programming 0, I feel it is necessary to comb it again:

1. The append () method adds a data item to the end of the list.

For example, add the "Gavin" item to 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 adds a data set to the end of the list.

For example, add "Kavin" and "Jack" and "Chapman" to the end of the students list, on top of example 1.


>>> 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 is the addition of a data item to a particular location.

For example, add "Gilliam" before "Palin" in the original students list.


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

students.insert (1, 'Gillam') 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.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: