The Del, Remove,pop difference of the python array

Source: Internet
Author: User

Take a=[1,2,3] For example, it seems to use Del, remove, pop an element 2 after a is all for [1,3], as follows:

  1. >>> a=[1,2,3]
  2. >>> A.remove (2)
  3. >>> A
  4. [1, 3]
  5. >>> a=[1,2,3]
  6. >>> del a[1]
  7. >>> A
  8. [1, 3]
  9. >>> a= [1,2,3]
  10. >>> A.pop (1)
  11. 2
  12. >>> A
  13. [1, 3]
  14. >>>

So what's the difference between Python and the list del, remove, and pop operations?

First, remove is the first element that meets the criteria. Does not delete a specific index. The following example: This article from the Novell fan website http://novell.me

    1. >>> a = [0, 2, 2, 3]
    2. >>> A.remove (2)
    3. >>> A
    4. [0, 2, 3]

For Del, it is deleted based on the index (where the element is), as in the following example:

    1. >>> a = [3, 2, 2, 1]
    2. >>> del a[1]
    3. [3, 2, 1]

The 1th element is a[0]--is counted starting at 0. Then a[1] refers to the 2nd element, which is the value 2.

Finally, we'll look at POPs.

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

Pop returns the value that you popped.

So use the appropriate method according to your specific needs. content from Http://novell.me

In addition, if they go wrong, the error mode is different. Note the following differences:

  1. >>> a = [4, 5, 6]
  2. >>> A.remove (7)
  3. Traceback (most recent):
  4. File "<stdin>", line 1, in <module>
  5. ValueError:list.remove (x): X not in list
  6. >>> del a[7]
  7. Traceback (most recent):
  8. File "<stdin>", line 1, in <module>
  9. Indexerror:list Assignment index out of range
  10. >>> A.pop (7)
  11. Traceback (most recent):
  12. File "<stdin>", line 1, in <module>
  13. Indexerror:pop index out of range

The Del, Remove,pop difference of the python array

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.