Familiar with Python-compatible list (3)

Source: Internet
Author: User
This is the third chapter of lis. As the saying goes, I don't know if I can finish the basic list knowledge at the beginning. Haha. In fact, if you write an article, you will delete this sentence after writing it. And I operate the list just like chatting with the viewer.

Insert an element to the list.

There is a method to append an element to the list. The append method can only add a new element to the last element in the list. For example:

>>> all_users = ["qiwsir","github"]>>> all_users.append("io")>>> all_users['qiwsir', 'github', 'io']

From this operation, the list can be changed at any time. The meaning of this change is only its size, that is, the number of elements contained and the content of the elements. It can be directly modified at any time without conversion. This is quite different from str. For str, The append of characters is not allowed. Please take note of the comparison, which is also an important difference between str and list.

Similar to list. append (x), list. insert (I, x) also adds list elements. You can add an element at any position.

My special guide column should be understood through official documents:

The Code is as follows:


List. insert (I, x)
Insert an item at a given position. the first argument is the index of the element before which to insert, so. insert (0, x) inserts at the front of the list, and. insert (len (a), x) is equivalent to. append (x ).


I will not translate this time. If you cannot understand English, how do you know your country? Be sure to read English with a strong scalp. Not only can you learn the program well, but also... (two thousand words are omitted here)

According to the instructions in the official documents, we will conduct the following experiment. Please refer to the experiment as follows:

>>> All_users ['qiwsir ', 'github', 'io'] >>> all_users.insert ("python") # list. insert (I, x) requires two parameters. If it is missing, the error Traceback (most recent call last) is returned: File"
 
  
", Line 1, in
  
   
TypeError: insert () takes exactly 2 arguments (1 given) >>> all_users.insert (0, "python") >>> all_users ['python', 'qiwsir ', 'github ', 'io'] >>> all_users.insert (1, "http: //") >>> all_users ['python', 'HTTP ://', 'qiwsir ', 'github', 'io'] >>> length = len (all_users) >>> length5 >>> all_users.insert (length, "algorithm") >>> all_users ['python', 'HTTP: // ', 'qiwsir', 'github ', 'io', 'algorithm']
  
 

Summary:

List. insert (I, x), insert the new element x to the front of list [I] in the original list.
If I = len (list), it means append after, it is equivalent to list. append (x)
Delete an element from the list

The elements in the list can be added and deleted. There are two methods to delete the list element:

list.remove(x)Remove the first item from the list whose value is x. It is an error if there is no such item.list.pop([i])Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

I am here to teach python. one habit is to use the physical learning method. If you are not familiar with physics at the beginning, you will not use this method, or your teacher will not use this teaching method. This method is: first experiment and then summarize the law.

First, experiment list. remove (x). Pay attention to the above description. This is a method that can delete list elements. The preceding description tells us that if x is not in list, an error is returned.

>>> All_users ['python', 'HTTP: // ', 'qiwsir', 'github ', 'IO', 'algorithm '] >>> all_users.remove ("http: // ") >>> all_users # It is true that" http: // "is deleted from ['python', 'qiwsir ', 'github', 'IO ', 'algorithm '] >>> all_users.remove ("tianchao") # The original list does not contain "tianchao". To delete it, an error is returned. Traceback (most recent call last): File"
 
  
", Line 1, in
  
   
ValueError: list. remove (x): x not in list
  
 

Note:

If it is deleted correctly, no feedback will be given. No message is good news.
If the deleted content is not in the list, an error is returned. Read the error message: x not in list
Is there a problem? If you can determine whether this element is in the list before deletion, and delete it if not, isn't it more intelligent?

If you think of this, you will make progress on the programming journey. Python does let us do this.

>>> All_users ['python', 'qiwsir ', 'github', 'IO ', 'algorithm '] >>> "python" in all_users # Here, we use in to determine whether an element is in the list. If yes, True is returned, otherwise, FalseTrue >>> if "python" in all_users:... is returned :... all_users.remove ("python ")... print all_users... else :... print "'python' is not in all_users "... ['qiwsir ', 'github', 'io', 'algorithm '] # deleted the "python" element >>>> if "python" in all_users :... all_users.remove ("python ")... print all_users... el Se:... print "'python' is not in all_users"... 'python' is not in all_users # no longer because it has been deleted.

The above code is two small programs. I am running in interactive mode, which is equivalent to a small experiment.

What if I delete another list. pop ([I? Take a look at the document and do the experiment.

>>> All_users ['qiwsir ', 'github', 'io', 'algorithm '] >>> all_users.pop () # list. pop ([I]), which contains [I] in parentheses, indicates that this sequence number is optional 'algorithm '# if not written, it is like this operation. By default, the last one is deleted, return the result >>> all_users ['qiwsir ', 'github', 'IO '] >>> all_users.pop (1) # Delete the element "github" 'github "> all_users ['qiwsir ', 'IO']> all_users.pop () 'IO '>>> all_users # There is only one element. The element number is 0 ['qiwsir'] >>> all_users.pop (1) # but you have to delete the element numbered 1, an error is returned. Note that the error message Traceback (most recent call last): File"
 
  
", Line 1, in
  
   
IndexError: pop index out of range # deleting an index out of range means that 1 is not in the list number range.
  
 

Leave a question for the reader. If you want to move forward, can you determine whether the number to be deleted is within the list length range (obtained by len (list? And then delete or not delete.

List is an interesting thing with rich connotations. It seems that the next lecture will continue with "list. And may make an interesting game. Please look forward.

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.