List knowledge points in Python

Source: Internet
Author: User
Tags python list
This article mainly summarizes some knowledge points in the Python list, which come from the technical documentation on the IBM official website. For more information, see Python list

When I introduced Python tuple, I used an analogy to compare it to a bag. you can store different things in the bag. Python list is very similar to this, so its functions are similar to those of bags. The difference is that you can use square brackets to create a list, as shown in listing 1.
Listing 1. create a list in Python

>>> l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> l[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> type(l)
 
  >>> el = []  # Create an empty list>>> len(el)0>>> sl = [1]  # Create a single item list>>> len(sl)1>>> sl = [1,]  # Create a single item list, as with a tuple>>> len(sl)1
 

This example shows how to create a simple list containing ranges from 0 to 9 (including 0 and 9), and how to create an empty list and a list containing a single entry. If you still remember, create a single tuple with a comma after a single entry. This is a necessary condition for distinguishing a single tuple from a method call, which will be discussed in detail in future articles. List is unnecessary, although a single comma is allowed.

As usual, to get more information about the Python topic, you can use the built-in help interpreter, for example, listing 2 shows the help description of how to start the list class.
Listing 2. getting help on the list

>>> help(list)Help on class list in module __builtin__:class list(object) | list() -> new list | list(sequence) -> new list initialized from sequence's items |  | Methods defined here: |  | __add__(...) |   x.__add__(y) <==> x+y |  | __contains__(...) |   x.__contains__(y) <==> y in x | ...

If you carefully observe the description of the list class in listing 2, you will see two different constructor: one without a parameter, and the other accepts a sequence class as a parameter. Therefore, you can create a list by using constructors and square brackets to simplify the symbols. This provides great flexibility because you can easily convert existing sequences, such as tuple or string, to list, as shown in listing 3. However, please note that the passed parameter must be a sequence -- and not just an object sequence -- otherwise, an error will occur. For any sequence type, you can use the len method to easily find the number of entries in the sequence.
Listing 3. directly create a list object

>>> l = list()>>> type(l)
 
  >>> len(l)0>>> l[]>>> l = list((0, 1, 2, 3, 4, 5, 6, 7, 8, 9))  # Create a list from a tuple>>> l[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> len(l)10>>> l = list([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])  # Create a list from a list>>> l[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> len(l)10>>> l = list(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)   # Error: Must pass in a sequenceTraceback (most recent call last): File "
  
   ", line 1, in ?TypeError: list() takes at most 1 argument (10 given)>>> l = list("0123456789") # Create a list from a string>>> l['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']>>> type(l)
   
    >>> len(l)10
   
  
 

As you can see, creating a list is very easy. if you haven't tried it yet, you can try it now. You can not only pass the sequence directly to the constructor, but also pass the variables with tuples or strings to the list constructor.

Obviously, the main reason why a sequence is useful is that it can easily access entries in the sequence. If you still remember the discussion of tuple, you can know that you can access an entry at a time in the sequence or by slicing the entry. Python list can also use the same technology, as shown in listing 4.
Listing 4. access entries from list

>>> l = list([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>>> l[0]     # Get the first item in the list0>>> type(l[0])
 
  >>> l[5]     # Get the sixth item in the list5>>> l[1:5]    # Get the second through fifth items[1, 2, 3, 4]>>> type(l[1:5])
  
   >>> l[0::2]   # Get every second item [0, 2, 4, 6, 8]>>> l[0], l[1], l[2]  (0, 1, 2)
  
 

As we have learned in previous articles, slice is a very useful concept. its general form is l [start: end: step]. start and end are the start and end indexes respectively, and step is the number of entries to be crossed during slicing. In addition, you can use a negative value to end the index, that is, count back from the end of the sequence. Another useful feature is to handle errors in a suitable way (such as exceeding the length of the sequence ). As shown in the previous example, you can also ignore one or more values of the three values used in the slice. For example, I did not use the end index in slice l [0: 2.

Variable sequence

At the beginning of this article, I mentioned that the main difference between list and tuple is that list is a variable sequence, which means that you can not only access entries in list conveniently, they can also be easily modified. However, this causes a concurrency problem: you can only modify entries in the sequence. You can use the append method to add entries to the sequence, as shown in listing 5.
Listing 5. modifying a list

>>> l = []>>> l[0] = 0   # The list is emptyTraceback (most recent call last): File "
 
  ", line 1, in ?IndexError: list assignment index out of range>>> l.append(0)>>> l[0]>>> l[0] = 1>>> l[1]
 

As demonstrated in the previous example, an error occurs when you try to modify a list entry that does not exist. This is significant and demonstrates the Python method generation error. When the problem is serious, an error is generated. if the problem is small and can be easily handled, ignore it.
Heterogeneous variable sequence

You may want to learn more complex modifications. By combining the knowledge of slicing and how to modify the list, you have gained an important insight: you can modify the list in multiple ways. Like tuple, a list can hold different types of data (or objects of different types). This is what I call a heterogeneous variable sequence. These two features are described in listing 6 in a more complete way.
Listing 6. heterogeneous variable list

>>> l=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> l[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> l[2] = 2>>> type(l[2])
 
  >>> l[2] = "two"   # Change the type of an element>>> ,ype(l[2])
  
   >>> l[0, 1, 'two', 3, 4, 5, 6, 7, 8, 9]>>> l[2] = l[2:5] * 2 >>> l[0, 1, ['two', 3, 4, 'two', 3, 4], 3, 4, 5, 6, 7, 8, 9]>>> del(l[2])     # Remove single element>>> l[0, 1, 3, 4, 5, 6, 7, 8, 9]>>> l[1:3] = []    # Remove a slice>>> l [0, 4, 5, 6, 7, 8, 9]
  
 

It is quite easy to modify entries in the list: you can set the value of an entry as appropriate, or even set it to another type, such as string or another list. You can also use the repeated operator to recognize it as a multiplication operator to build a larger list from a small segment.

The previous example shows how to add elements to the list and modify entries in the list. The previous example also demonstrates how to delete objects from the list. The first method to delete an entry is to use the del method. You can use this method to delete an entry or a range of entries. You can also use flexible and powerful slicing methods to delete slices from the list.
Array

In the previous example, you can see that list can contain another list as an entry. If you extend this example, you may want to know what will happen if each entry is replaced by a list. The result is an array or a matrix in mathematics. Listing 7 shows how to use list to maintain a two-dimensional (2-D) or three-dimensional (3-D) array.
Listing 7. list as an array

>>> al = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]>>> al[[0, 1, 2], [3, 4, 5], [6, 7, 8]]>>> al[0][0]     # First element in 2D array0>>> al[2][2]     # Last element in 2D array8>>> al[1][2]5>>> al = [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]>>> al[[[0, 1], [2, 3]], [[4, 5], [6, 7]]]>>> al[0][0][1]1>>> len(al)      # Length of outer dimension2>>> len(al[0])    # Length of middle dimension2>>> len(al[0][0])   # Length of inner dimension2

Other list operations

List objects have many useful methods that can be applied to existing lists. For example, you can reverse all entries in the list or sort the list. However, remember that the focus of these operations is that they are local operations, which means they modify the list for which they are called. Therefore, if you try to create a new list and set it to the result of calling one of these methods, an empty list will be obtained.

In addition to simulating arrays, list can also be used to simulate other data structures. For example, the append and pop methods operate the list function either in the first-in-first-out (FIFO) data structure (also known as the queue) or in the last-in-first-out (LIFO) mode) data structure (also called stack ). You can set entries to pop-up (delete and return) from the list. The pop method supports these functions. If the first item of the list is displayed, it is a queue. if the last item of the list is displayed, it is a stack, as shown in listing 8.
Listing 8. manipulating list

>>> l=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> id(l) # This is the object id for our current list4525432>>> l.reverse()    # Reverse the list>>> l[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]>>> id(l) # The id is the same, modified list in place.4525432>>> l.sort()     # Sort the list in numerical order>>> l[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> id(l) # Modified the existing list4525432>>> l.index(5)    # Same as l[5]5>>> l.count(0)    # How many times does '0' occur in the list1>>> l.pop()      # Take off the last item (Stack)9>>> l[0, 1, 2, 3, 4, 5, 6, 7, 8]>>> l.pop(5)     # Take out the fifth element5>>> l[0, 1, 2, 3, 4, 6, 7, 8]>>> l.pop(0)     # Take the first item off the list (Queue)0>>> l[1, 2, 3, 4, 6, 7, 8]

List: Slice and slice

This article introduces the list, which is a container object that can be easily modified and can hold different types of data. Because of its flexibility, list is one of the most common structures in Python programming languages. A list is like a pocket that can hold different types of data and can be changed as needed. You can use a list like an array to hold data in an organized manner. you can also use a list like a queue or a stack. In future articles, we will explore this spirit more deeply and introduce powerful programming technologies, that is, list understanding.

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.