python--List __python

Source: Internet
Author: User

Previously, we have explored the related operation of strings (python– strings). A list is the same as a string, and he is also a sequence, called a sequence, that stores an object's container in a certain order, and each sequence in the container is by default a subscript (index) corresponding to it. From this perspective, the list, of course, has the same character as a string in terms of the nature of the sequence. But their differences are more, for example, in the way they are stored, the types of objects they store, and so on. A list is also a sequence

We found that the list was created and accessed to satisfy the character similar to the string. 1. The creation of the list

As with creating strings, there are two types: direct assignment and the list () function

Alist = [1, 2, "we", [12.5, "how"]] # >>> A list of four elements
alist = [] # >>> Empty list
alist = List ("123") # >>> ["1", "2", "3"]

The list is written in the form of an object in the brackets "[]", which is separated by "," and, of course, if there is nothing inside the brackets, it means that an empty list has been created. One notable feature of the list in Python is that it can store any type of object (integer, floating-point, string, or even list itself, and so on), unlike strings, which can store only characters.

Also, it is important to note that when using the list () function, the incoming parameter must be iterative, such as passing in an integer, floating point number, will be an error. 2. Access to the list

Two methods: through the subscript;

Alist = [1, 2, 3, 4, 5]
alist[-1] # >>> 5
alist[0:2] # >>> [1, 2]
Alist[0::2] # >>> [1, 3, 5]
ALIST[::-1] # >>> [5, 4, 3, 2, 1]

As with strings, index settings start at 0 and also have positive and negative indexes. Slices are also made up of three 3 parameters [Begin:end:step], which are exactly the same in the string, and are not detailed here (see: python– strings) related operations

We already know that strings are immutable, that is, what we do about updating strings is actually done by creating a new string object. But the list is more convenient, he is variable, you can add, delete, modify the elements of the list at any time. Plus, the list we talked about can store any type of object, so it's conceivable that the list provides us with this very handy data storage structure that will greatly simplify programming. 1. Add

The Append () function enables you to add elements directly to the end of the list, and the syntax is very simple.

Alist = []
alist.append (1) # >>> alist = [1]
alist.append ("we") # >>> alist = [1, ' we ']

Note that this is where the list alist itself changes, rather than creating another list, which is essentially different from the string. 2. Insert

The append () function can only add elements at the end of the list, and sometimes we need to insert elements in certain places, which requires the insert () function.

Alist = ["I", "Python"]
Alist.insert (1, "wrote") # at position 1 Insert string Object "wrote"
print (alist) # >>> ["I", "wrote" , "Python"]

Insert () This is the structure of the () function: Insert (index, obj). The first parameter represents the position to insert, and the second parameter represents the element 3 to be inserted . Delete

Two methods of deletion: Remove (obj) and pop (index)

You can see the difference in the usage scenario from the parameters of the two functions. If we know that we want to delete the value of the object itself, is removed directly using remove (obj), and if you know where you want to delete the object, use Pop (index) to delete the element based on the index, or the default index of 1, or the last element of the list, if the index you want to delete is not given.

We'll see what we can do with it.

Alist = [1, 2, 1, 3, 4, 5, 6]
Alist.remove (1) # >>> Delete First 1 element
print (alist) # >>> [2, 1, 3, 4, 5 , 6]
alist.pop (0) # >>> Delete the element of index = 0, which is the 2
print (alist) # >>> [1, 3, 4, 5, 6] in alist now.

It should be noted that the Remove (obj) function has no return value (or that his return value is None), such as:

Alist = [1, 2, 1, 3, 4, 5, 6]
print (Alist.remove (1)) # >>> None 
                       # >>> because only the first element in Alist is deleted, but the letter The number itself does not return a value

The POP (index) function returns the value that was deleted:

Alist = [1, 2, 1, 3, 4, 5, 6]
print (Alist.pop ()) # >>> 6
                   # >>> return the deleted element
4. Revise

By subscript, you can modify the corresponding elements of the list

Alist = [1, 2, 3, 4]
alist[1] = 3 # >>> [1, 3, 3, 4]
alist[-1] = 3 # >>> [1, 3, 3, 9]

Of course, you can also use slices to implement batch modification, but this approach should be avoided as much as possible.

Alist = [1, 2, 3, 4]
alist[0:2] = [3, 4]
print (alist) # >>> [3, 4, 3, 4]

Because a little attention, there will be mistakes, for example, or just the example:

Alist = [1, 2, 3, 4]
B = alist[0:2] # >>> B = [1, 2]; the equivalent of copying a portion of alist, then referring to
b[1 with b] = 3
print (b) # ;>> [1, 3]
print (alist) # >>> [1, 2, 3, 4] alist did not change

So we should try to avoid this batch modification. 5. Expand

We can also combine a list with another list (which can be another sequence) in two ways:

(1) Extend () function

Alist = [1, 2, 3, 4]
alist.extend ([5, 6, 7, 8])
print (alist) # >>> [1, 2, 3, 4, 5, 6, 7, 8]
Alist.ext End ("we")
print (alist) # >>> [1, 2, 3, 4, 5, 6, 7, 8, "W", "E"]

The Extend () function actually adds content to the original list and does not create a new list.

(2) + operator

The + operator acts as a string in the list, representing the connection. and can only operate between objects of the same type, the list of + can only be added to the list

Alist = [1, 2, 3, 4]
alist + = [5, 6, 7, 8]
print (alist) # >>> [1, 2, 3, 4, 5, 6, 7, 8]

It is important to note that using the + operator for a list must assign a value to this combined result (which is actually a new object). This is the same as the integer, the addition of the floating-point number, and the link to the string. For example, an operation like the following is illegal:

Alist = [1, 2, 3]
alist + [4, 5] # >>> invalid!
6. Operator

In the extension above, the + operator has been introduced, as is the case with the string, and the list also has the repeat operator * and the member operator in, not in, and is used in the same way as in the string, here, just giving an example

Alist = [1, 2]
alist *= 3
print (alist) # >>> [1, 2, 1, 2, 1, 2]
print (1 in alist) # >>> True
Print (2 not in alist) # >>> True
Common Functions

Here's a list of related built-in functions: Append (), remove (), pop (), extend (), insert (), and I'll introduce you to something else. 1. Length and size value

Alist = [3, 1, 2, 9, 8]

# len () function to fetch list length
print (len (alist)) # >>> 5

# max (), Min () to fetch the maximum minimum value of a list
print (Max (alist)) # >>> 9
print (min (alist)) # >>> 1

When you ask for a size value, the elements you want to store in the list are the same type, or different types (such as integer and floating-point) that are comparable in size. 2. Flip and sort

Strings are immutable types, so the flip of a string is actually a new object, and the list is mutable, so we can flip and sort the list itself.

(1) Flip

Alist = [1, 2, 3, 4, 5]
alist.reverse () # Flip the list, but the function itself does not return a value, just flip the list
print (alist) # >>> [5, 4, 3, 2, 1]

Of course, we can also generate a new, flipped list from the function reversed () without changing the original list.

Alist = [1, 2, 3, 4, 5]

temp = reversed (alist) # >>> freshman became an object, and this object is not a list type, but it can be accessed for the I in temp through A For loop
:
    print (i) # >>> sequentially output: 5, 4, 3, 2, 1

print (alist) # >>> [1, 2, 3, 4, 5], original list unchanged

You can also flip a list by slicing it

Alist = [1, 2, 3, 4, 5]

temp = alist[::-1] # temp is a newly generated list
print (temp) # >>> [5, 4, 3, 2, 1]

print (AL IST) # >>> [1, 2, 3, 4, 5], original list unchanged

(2) Sorting

Similar to the maximum minimum value of a fetch list, when sorting a list, you also need to require that the elements that the column stores are of the same type or of different types that can be compared.

Two functions to implement sort: sort (), sorted ()

Alist = [3, 1, 2, 9, 8]
alist.sort () # >>> alist in place (in ascending order), but the function itself has no output, just completes a function, with reverse () Like
print ( alist) # >>> [1, 2, 3, 8, 9]
Alist = [3, 1, 2, 9, 8]
B = Sorted (alist) # >>> created a new list b,b is the alist order of appearance
print (b) # >>> [1, 2, 3, 8, 9]
print (alist) # >>> [3, 1, 2, 9, 8] original list alist unchanged

Note: the sorted () function is different from the previous reversed () function, sorted () is directly generated a new list, not through the For loop, can also be printed directly.

Of course, the sort () function is the default ascending order, but we can also order the descending order by changing the corresponding parameters.

Alist = [3, 1, 2, 9, 8]
Alist.sort (reversed=true) # >>> setting Parameters Reversed=true Implementing descending order
print (alist) # >>& Gt [9, 8, 3, 2, 1]

In fact, the use of the sort () function has many variants by setting parameters, which we'll talk about later when we have a specific question. 3. Summation and Statistics

(1) The list is summed up by the sum () function, of course, to satisfy the elements stored in the list are integral or floating-point

Alist = [1, 2.33]
print (SUM (alist)) # >>> 104.33

(2) The list completes the statistics of the elements in the list through the count () function

Alist = [1, 2, 1, [1, 2], [1, 2]]
print (Alist.count (1)) # >>> 2
print (Alist.count ([1, 2])) # >>> 2
Print (Alist.count ([2, 1])) # >>> 0
4. Emptying and copying

(1) empty

It is OK to directly assign an empty list, but the principle of doing so is to let the variable name refer to a new empty list, not a true sense of empty

alist= [1, 2, 3]
alist = [] # >>> references a new empty list
print (alist) # >>> []

The clear () function can be used in the real sense of emptying the list

alist= [1, 2, 3]
print (ID (alist)) # >>> 4328406280
alist.clear ()
print (alist) # >>> []< C10/>print (ID (alist)) # >>> 4328406280, same location, clear in situ

(2) Copy
Two methods can be implemented: slicing and copy () functions

slices [:]

alist= [1, 2, 3]
B = alist[:]
b[0] = 8
print (b) # >>> [8, 2, 3]
print (alist) # >>> [1, 2 , 3] Modify b,alist not affected

function copy ()

alist= [1, 2, 3]
B = alist.copy ()
print (ID (alist)) # >>> 4362226952
print (ID (b)) # >>> 4362 264520<

Copy the list 5 enumerate () and zip () in another location, just like the slice method.

The use of these two functions is the same as the string, see the previous blog (python– string), here, just give an example:

A = [' I ', ' he ', ' she ']
b = [' My ', ' his ', ' her '] for
I, J-in Enumerate (a):
    print (I, j) # >>> output 0 in turn I ", 1" he ", 2" she "for
I, J in Zip (A, b):
    print (I, j) # >>> sequentially output" I "," my "," she "," his "," she "," her "

The point to note is that if you want to pass multiple elements to the zip () function in a sequence, you need to precede the sequence name with *, otherwise the result will not appear:

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for
i in Zip (*a):
    print (i) # >>> output sequentially (1, 4, 7), (2, 5, 8), 9)

And if you don't add *, the function will think that there is only one input

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for
i in Zip (a):
    print (i) # >>> sequentially output ([1, 2, 3],), ([4, 5, 6],), ([ 7, 8, 9],)
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.