Python list Add new element

Source: Internet
Author: User
Tags python list

Append () and insert ()

Add new Element
Now, there are 3 students in the class:
>>> L = [' Adam ', ' Lisa ', ' Bart ']
Today, the class transferred to a new classmate Paul, how to add new students to the existing list?
The first option is to append the new classmate to the end of the list by using the Append () method of the list:
>>> L = [' Adam ', ' Lisa ', ' Bart ']
>>> l.append (' Paul ')
>>> Print L
[' Adam ', ' Lisa ', ' Bart ', ' Paul ']
Append () always adds a new element to the tail of the list.
What if Paul says he is always on the test and asks to be added to the first place?
The method is to use the list's insert () method, which accepts two parameters, the first parameter is the index number, and the second parameter is the new element to be added:
>>> L = [' Adam ', ' Lisa ', ' Bart ']
>>> LInsert (0, ' Paul ')
>>> Print L
[' Paul ', ' Adam ', ' Lisa ', ' Bart ']
L.insert (0, ' Paul ') means that ' Paul ' will be added to the position of index 0 (i.e. the first one), while Adam, who originally indexed 0, and all the classmates behind it, automatically move backwards.

Python list Add new element

Related Article

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.