Summary of common methods for Python operation List

Source: Internet
Author: User
The following is a list of common methods and small examples: 1Append adds elements at the end of the list. you need to add elements at the end of the list. Note the following: the parameters added in Aappend list lists the list of common methods and operations and small examples:

1. Append

To add an element at the end of the list, you must add the element at the end of the list. Note the following points:

A. The parameters added in append are as A whole.

>>> Name = list ("scott ")

>>> Name

['S ', 'C', 'O', 'T', 't']

>>> Name. append (list ("tiger "))

>>> Name

['S ', 'C', 'O', 'T', 'T', ['', 'T',' I ', 'G ', 'E', 'R']

The obtained values are not: ['s ', 'C', 'O', 'T', 'T', '', 'T ', 'G', 'e', 'R']

If you want to append this method, you can try the multipart assignment (or the extend method mentioned below ):

>>> Name = list ("scott ")

>>> Name

['S ', 'C', 'O', 'T', 't']

>>> Name [len (name):] = list ("tiger") # append from the end

>>> Name

['S ', 'C', 'O', 'T', 'T', '', 'T',' I ', 'G', 'e ', 'R']

B. append can only add one element at a time.

>>> Name = list ("scott ")

>>> Name

['S ', 'C', 'O', 'T', 't']

>>> Name. append ("A", "B") # An error is returned when multiple elements are added.

Traceback (most recent call last ):

File "", line 1, in?

TypeError: append () takes exactly one argument (2 given)

>>> Name. append ("")

>>> Name

['S ', 'C', 'O', 'T', 'T', 'A']

2. Count

Count the number of times an element appears in the list

>>> Name = list ("scott ")

>>> Name

['S ', 'C', 'O', 'T', 't']

>>> Name. count ('s ')

>>> Name. count ("t ")

>>> Name. count ("")

>>> Name. append (list ("Python "))

>>> Name

['S ', 'C', 'O', 'T', 'T', ['P', 'y', 'T', 'H ', 'o', 'n']

>>> Name. count (['P', 'y', 'T', 'H', 'O', 'n'])

3. Extend

Append multiple values of another sequence to the original list

>>> Name = list ("scott ")

>>> Name

['S ', 'C', 'O', 'T', 't']

>>> Name. extend (list ("tiger "))

>>> Name

['S ', 'C', 'O', 'T', 'T', '', 'T',' I ', 'G', 'e ', 'R']

Of course, we can use the multipart value assignment to implement:

>>> Name = list ("scott ")

>>> Name

['S ', 'C', 'O', 'T', 't']

>>> Name [len (name):] = list ("tiger ")

>>> Name

['S ', 'C', 'O', 'T', 'T', '', 'T',' I ', 'G', 'e ', 'R']

At this time, the friends will think that we can directly use the operator "+", but it is more convenient:

>>> Name = list ("scott ")

>>> Pwd = list ("tiger ")

>>> Name + pwd

['S ', 'C', 'O', 'T', 'T', '', 'T',' I ', 'G', 'e ', 'R']

>>> Name

['S ', 'C', 'O', 'T', 't']

From the output of these three operations, we can see that:

Both extend and multipart assignment modify the original list. In contrast, extend is more readable, while the operator "+" generates a new list without affecting the original list.

You can use the operator "+" to generate a new list without affecting the original list ".

4. Index

Locate the index location of the first (note that it is the first) matching item of a value from the list.

>>> Name = list ("scott ")

>>> Name

['S ', 'C', 'O', 'T', 't']

>>> Name. index ('t') # The index location of the first letter t is 3.

>>> Name. index ('A ')

Traceback (most recent call last ):

File "", line 1, in?

ValueError: list. index (x): x not in list

>>> 'A' in name

False

>>> 'A' not in name

True

From the output, we can see that index is the index location of the first matching item. if the searched element is not in the list, an error is returned (will it be better to return-1 ?), If you want to avoid reporting

An error occurs. we can first use the in operation to determine whether an element is in a list. if so, perform the index operation.

5. Insert

Used to insert an object to the list. The first parameter is the index position and the second parameter is the inserted element object.

>>> Name = list ("scott ")

>>> Name

['S ', 'C', 'O', 'T', 't']

>>> Name. insert (2, 'Tiger ') # insert the string tiger where the index is 2

>>> Name

['S ', 'C', 'Tiger', 'O', 'T', 't']

We can also assign values by using multipart assignment:

>>> Name = list ("scott ")

>>> Name

['S ', 'C', 'O', 'T', 't']

>>> Name [2] = ['Tiger ']

>>> Name

['S ', 'C', 'Tiger', 'O', 'T', 't']

>>> Name [2] = 'Tiger'

>>> Name

['S ', 'C', 'T',' I ', 'G', 'e', 'R', 'Tiger', 'O ', 'T', 't']

Note that if you insert an element, you must use [] to enclose it. Otherwise, if you directly use a string, you need to insert the string list and add it after the index position.

Of course, the readable score of insert is given a high value.

6. Pop

Removes an element from the list (the last element) and returns the value of this element.

>>> Name = list ("scott ")

>>> Name

['S ', 'C', 'O', 'T', 't']

>>> Name. pop ()

'T'

>>> Name

['S ', 'C', 'O', 't']

>>> Name. append ("t ")

>>> Name

['S ', 'C', 'O', 'T', 't']

Partition assignment simulates pop:

>>> Name = list ("scott ")

>>> Name

['S ', 'C', 'O', 'T', 't']

>>> Name [len (name)-1:] = []

>>> Name

['S ', 'C', 'O', 't']

The above uses pop and append to simulate the stack's first-in-first-out LIFO.

7. Remove

Remove the first match of a value in the list: If there are two equal elements, only one matching element is removed. If an element does not exist in a list, an error is returned, and only

Removes an element.

>>> Name = list ("scott ")

>>> Name

['S ', 'C', 'O', 'T', 't']

>>> Name. remove ("t") # remove the first t

>>> Name

['S ', 'C', 'O', 't']

>>> Name. remove ("A") # An error is reported if no one exists.

Traceback (most recent call last ):

File "", line 1, in?

ValueError: list. remove (x): x not in list

>>> "A" not in name

True

>>> Name. remove ("s", "c") # only one element can be removed at a time.

Traceback (most recent call last ):

File "", line 1, in?

TypeError: remove () takes exactly one argument (2 given)

8. Revense

Reverse the elements in the list

>>> Name = list ("scott ")

>>> Name

['S ', 'C', 'O', 'T', 't']

>>> Name. reverse ()

>>> Name

['T', 'T', 'O', 'C', 's']

9. Sort & Sorted

The sort method is used to sort the list. modifying the original list does not return a copy of the sorted list.

>>> Result = [8, 5, 5, 3, 9]

>>> Result. sort ()

>>> Result

[3, 5, 5, 8, 9]

If we want to return a copy of the sorted list without affecting the original list, we can assign values to the original list first (you can assign values to copy the list using multipart assignment), and then

Perform the sort operation on the copied list. Another method is to use the sorted function, which returns the sorted list copy:

>>> Result = [8, 5, 5, 3, 9]

>>> Result2 = sorted (result)

>>> Result

[8, 5, 5, 3, 9]

>>> Result2

[3, 5, 5, 8, 9]

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.