List Knowledge point rollup _python in Python

Source: Internet
Author: User
Tags data structures stdin python list

Python List

When I introduce the Python tuple, I use the analogy method, compare it to a bag, you can store different things in the bag. The Python list is very similar to this, so its function is very similar to the function of the bag. One thing is different, though, 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]
>>> Typ E (L)
<type ' list ' >
>>> 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 0 to 9 (including 0 and 9) and how to create an empty and a list that contains a single entry. If you remember, the tuple of creating a single entry also needs to be followed by a comma after a single entry. This is a necessary condition for distinguishing individual entry tuple from method invocation, which will be discussed in detail in later articles. For a list, it is unnecessary, although a single comma is also allowed.

As always, to get more information about Python topics, you can use the built-in Help interpreter, for example, listing 2 shows how to start the Help description for the list class.
Listing 2. Get 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 look closely at the description of the list class in Listing 2, you'll see that it provides two different constructors: one with no arguments and the other with a sequence class as an argument. Therefore, you can create a list by using constructors and square brackets to simplify symbols. This provides a lot of flexibility because you can easily convert an existing sequence, such as tuple or string, to a list, as shown in Listing 3. Note, however, that the passed argument must be a sequence--and not just a sequence of objects--otherwise there will be an error. For any sequence type, you can use the Len method to easily find the number of entries in the sequence.
Listing 3. Create a list object directly

>>> L = list ()
>>> type (l)
<type ' list ' >
>>> 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)
>>> 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]
>>> le N (L)
>>> l = List (0, 1, 2, 3, 4, 5, 6, 7, 
8, 9)   # Error:must pass in a sequence
Trac Eback (most recent):
 File "<stdin>", line 1, in?
Typeerror:list () takes at most 1 argument (given)
>>> L = List ("0123456789") # Create a list from a stri ng
>>> l
[' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']
>>> type (l)
<type ' Li St ' >
>>> len (l)
10

As you can see, creating a list is easy, and if you haven't tried it, try it now. Not only can you pass a sequence directly to a constructor, you can also pass a variable that has a tuple or string to the list constructor.

Obviously, the main reason the sequence is more useful is that it makes it easy to access the entries in the sequence. If you remember the discussion of tuple, you know that you can access an entry in a sequence at one time or by slicing an item to access it. The Python list can also use the same technique, 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 The "the"
>>>> type (l[0])
<type ' int ' >
>>> l[5]     # Get the sixth item in the list
5
>>> L[1:5]    # Get the second through fifth items
[1, 2, 3, 4]
>>> type (L[1:5])
<t ype ' list ' >
>>> l[0::2]   # Get every second item 
[0, 2, 4, 6, 8]
>>> l[0], l[1], l [2]  
(0, 1, 2)

As I've learned in previous articles, slicing is a very useful concept, and its general form is l[start:end:step], where start and end are the beginning and ending indexes, and step is the number of entries to cross when slicing. In addition, you can use negative values for the end index, that is, to count back from the end of the sequence. Another useful feature is to handle errors in a very appropriate way (such as exceeding the length of a sequence). As shown in the previous example, you can also choose to ignore one or more of the three values used in the slice. For example, I did not use the end index in slice l[0::2].

A variable sequence

At the beginning of this article, I mentioned that the main difference between list and tuple is that the list is a mutable sequence, which means that you not only have easy access to the entries in the list, but you can easily modify them. But this can cause a complication: You can only modify entries in the sequence. To add an entry to the sequence (not just to modify the entry), use the Append method, as shown in Listing 5.
Listing 5. Modify List

>>> L = []
>>> l[0] = 0   # The list is empty
traceback (most recent called last):
 File " ;stdin> ", line 1, in?
Indexerror:list Assignment index out of range
>>> l.append (0)
>>> l
[0]
>> > l[0] = 1
>>> l
[1]

As the previous example shows, attempting to modify a nonexistent list entry can result in an error. This is significant and demonstrates how the Python method generates errors. When the problem is more serious, an error occurs, ignoring it if the problem is small and can be easily handled.
heterogeneous, variable sequences

You may want to know more complex modifications. By synthesizing slicing knowledge and how to modify the list's knowledge, you should already have a very important insight: You can modify the list in a variety of ways. Like tuple, a list can hold different types of data (or different types of objects), which is what I call heterogeneous mutable sequences. These two features are described more fully in Listing 6.
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])
<type ' int ' >
>>> l[2] = "Two"   # change the type of a element
   >>>, Ype (l[2])
<type ' str ' >
>>> 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]

Modifying an entry in the list is fairly easy: you can set the value of the entry appropriately, or even set it to a different type, such as a string or another list. You can also use the repeating operator to recognize the operator as a multiplication operator so that you can build a larger list from a small fragment.

The previous example shows you how to add elements to the list and how to modify the entries in the list. The previous example also shows how to remove an object from the list. The first way to delete an entry is to use the Del method. Use this method to delete an entry or a range of entries. You can also use a flexible and powerful slicing method to remove slices from the list.
Array

As you can see in the previous example, the list can contain another list as an entry. If you extend this example, you might want to know what happens to each entry by replacing it with a list. The result is an array or, more mathematically, a matrix. Listing 7 shows how to use a list to maintain a two-dimensional (2-d) or three-dimensional 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]     # in 2D array
0
>>> al[2][2] # last     element in 2D array
8
;>> 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 Dimensio N
2
>>> len (al[0])    # Length of Middle Dimension
2
>>> len (al[0][0))   # Length of inner dimension
2

Other list actions

The list object has a number of useful methods that can be applied to an existing list. For example, you can reverse all entries in the list or sort list. However, one important thing to remember about these operations is that they are in-place operations, which means that they modify the list that they are called against. Therefore, if you try to create a new list and set it to be the result of a call to one of these methods, you get an empty list.

The

List can be used in addition to simulating arrays and can be used to simulate other data structures. For example, the Append and Pop methods operate on the list function either as FIFO data structures (also known as queues) or as LIFO (LIFO) data structures (also known as stacks). The Pop method supports these features by allowing you to set up entries to eject (delete and return) from the list. If the first item of the list pops up, it is a queue; Conversely, if the last item in the list pops up, it's a stack, as shown in Listing 8.
Listing 8. Manipulate list

>>> l=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ID (L) # This is the object ID to our current list
4525 432
>>> 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.
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 list
4525432
>>> l.index (5)    # Same as l[5]
5
>>> l.count (0)    # How 
many times does ' 0 ' occur in the list
1
>>> L.pop () # Take off of the last      item (Stack)
9
>>> L
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> ; L.pop (5)     # Take out the Fifth Element
5
>>> L
[0, 1, 2, 3, 4, 6, 7, 8]
>>> L.po P (0)     # Take The ' the ' The ' list (Queue)
0
>>> L
[1, 2, 3, 4, 6, 7, 8]

List: Slices and dice

This article describes the list, which is a container object that can be easily modified and can hold different types of data. Since it has considerable flexibility, it is not surprising that list is one of the most common structures in the Python programming language. The list is like a pocket that can accommodate different types of data and can be changed as needed. You can use the list as an array to hold the data in an organized way, and you can use the list just as you would with a queue or stack. This flexibility will be explored in more depth in future articles, as well as a powerful programming technique called 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.