Difference between python append, extend and insert, pythonappend

Source: Internet
Author: User

Difference between python append, extend and insert, pythonappend

Recently, I learned how to add more data to the list using the append (), extend (), and insert () methods.

Append and extend both require only one parameter and are automatically added to the end of the array. If multiple parameters need to be added, Arrays can be nested. However, append uses the nested array as an object,

Extend is to add the nested array content as multiple objects to the original array.

I think it is necessary for me to repeat it as a basic programmer:

1. The append () method adds 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 adds a data set at the end of the list.

For example, based on Example 1, "Kavin" and "Jack" and "Chapman" are added at 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 adds a data item before a specific position.

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

Because data items are stacked from the bottom up, the first data number in the stack is 0, and the second data number is 1, so it is students. insert (1, 'gillim ').

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

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.