Python common list data structure summary _python

Source: Internet
Author: User

This article summarizes some common object methods in the Python list List for beginners to reference or query, as follows:

1.list.append (x)

add element x to the end of the list, equivalent to A[len (a):] =[x, the code is as follows:

>>> a=[1,2,3,4,5]
>>> a
[1, 2, 3, 4, 5]
>>> a.append ( -2)
>>> A
[1, 2, 3, 4, 5,-2]

2. List.extend (L)

Add all the elements from one list to another list, equivalent to A[len (a):] = L, the code is as follows:

>>> a
[1, 2, 3, 4, 5,-2]
>>> l=[5,9,7]
>>> L
[5, 9, 7]
>>> A.extend (L)
>>> a
[1, 2, 3, 4, 5,-2, 5, 9, 7]

3. List.insert (i,x)

before inserting element x into index number I , the code is as follows:

>>> a
[1, 2, 3, 4, 5,-2, 5, 9, 7]
>>> A.insert (0,-3)
>>> a
[-3, 1, 2, 3, 4, 5, -2, 5, 9, 7]
>>> A.insert (Len (a), ten)
>>> a
[-3, 1, 2, 3, 4, 5,-2, 5, 9, 7, 10]

4. List.remove (x)

Delete element x (first occurrence) with the following code:

>>> a
[ -3, 1, 2, 3, 4, 5,-2, 5, 9, 7, ten]
>>> a.append (1)
>>> a
[-3, 1, 2, 3, 4, 5,-2, 5, 9, 7, 1]
>>> a.remove (1)
>>> A [-3, 2, 3, 4, 5, 2, 5,
9, 7, 10, 1]

5. List.count (x)

calculates the number of times element x appears , as follows:

>>> a
[ -3, 2, 3, 4, 5,-2, 5, 9, 7, ten, 1]
>>> a.count (3)
1

6. List.sort ()

to sort the list elements , the code is as follows:

>>> a.sort ()
>>> a
[-3,-2, 1, 2, 3, 4, 5, 5, 7, 9, 10]

7. List.reverse ()

To rearrange the elements in a table , the code is as follows:

>>> a
[ -3,-2, 1, 2, 3, 4, 5, 5, 7, 9, ten]
>>> a.reverse ()
>>> a
[10, 9, 7, 5, 5, 4, 3, 2, 1,-2,-3]

8. List.index (x)

returns the first index in the table that appears with a value of x , as follows:

>>> a
[9, 7, 5, 5, 4, 3, 2, 1,-2,-3]
>>> a.index (9)
1

9. List.pop (i)

specify location from the list I deletes the element and returns it, and if not, deletes the last element of the list and returns the element. The code is as follows:

 >>> a [9, 7, 5, 5, 4, 3, 2, 1,-2,-3] >>> a.pop (0) >>> A [9, 7, 5, 5, 4, 3, 2, 1,-2,-3] >>> A.pop ()-3 

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.