The difference between append, extend and insert

Source: Internet
Author: User

Recently, in the self-learning Python language, it was append (), extend (), and the Insert () method to see that more data was added to the list.

As the basis of programming 0 small white, feel the need to comb it again:

The 1.append () method refers to adding a data item at 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 ']

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

For example: in Example 1, the end of the students list continues to add three entries for "Kavin" and "Jack" and "Chapman".

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

The 3.insert () method refers to the addition of a data item in front of a specific location.

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

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

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

The difference between append, extend and insert

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.