12. List in python, 12. python list
First, let's see how the list is created:
a = ['scolia', 123]b = list('scolia',123)
There are two creation methods, but the first one is generally used.
The biggest difference between a list and a ancestor is that the list can be modified.
Old Rules: Using help (list) is really a good help () method.
Okay, come on, run the code.
Help on class list in module _ builtin __: class list (object) | list ()-> new empty list | list (iterable) -> new list initialized from iterable's items | Methods defined here: | _ add __(...) | x. _ add _ (y) <==> x + y | _ contains __(...) | x. _ contains _ (y) <=> y in x | _ delitem __(...) | x. _ delitem _ (y) <=> del x [y] | _ delslice __(...) | x. _ delslice _ (I, j) <=> del x [I: j] | Use of nega Tive indices is not supported. | _ eq __(...) | x. _ eq _ (y) <=> x = y | _ ge __(...) | x. _ ge _ (y) <==> x> = y | _ getattribute __(...) | x. _ getattribute _ ('name') <=> x. name | _ getitem __(...) | x. _ getitem _ (y) <=> x [y] | _ getslice __(...) | x. _ getslice _ (I, j) <=> x [I: j] | Use of negative indices is not supported. | _ gt __(...) | x. _ gt _ (y) <==> x> y | _ iadd __(...) | x. _ iadd __ (Y) <=> x + = y | _ imul __(...) | x. _ imul _ (y) <=> x * = y | _ init __(...) | x. _ init __(...) initializes x; see help (type (x) for signature | _ iter __(...) | x. _ iter _ () <=> iter (x) | _ le __(...) | x. _ le _ (y) <=> x <= y | _ len __(...) | x. _ len _ () <=> len (x) | _ lt __(...) | x. _ lt _ (y) <==> x <y | _ mul __(...) | x. _ mul _ (n) <=> x * n | _ ne __(...) | x. _ ne _ (y) <=> x! = Y | _ repr __(...) | x. _ repr _ () <=> repr (x) | _ reversed __(...) | L. _ reversed _ () -- return a reverse iterator over the list | _ rmul __(...) | x. _ rmul _ (n) <=> n * x | _ setitem __(...) | x. _ setitem _ (I, y) <=> x [I] = y | _ setslice __(...) | x. _ setslice _ (I, j, y) <=> x [I: j] = y | Use of negative indices is not supported. | _ sizeof __(...) | L. _ sizeof _ () -- size of L in memory, in bytes | append (...) | L. append (object) -- append object to end | count (...) | L. count (value)-> integer -- return number of occurrences of value | extend (...) | L. extend (iterable) -- extend list by appending elements from the iterable | index (...) | L. index (value, [start, [stop])-> integer -- return first index of value. | Raises ValueError if the value is not present. | insert (...) | L. insert (index, object) -- insert object before index | pop (...) | L. pop ([index])-> item -- remove and return item at index (default last ). | Raises IndexError if list is empty or index is out of range. | remove (...) | L. remove (value) -- remove first occurrence of value. | Raises ValueError if the value is not present. | reverse (...) | L. reverse () -- reverse * in place * | sort (...) | L. sort (cmp = None, key = None, reverse = False) -- stable sort * in place *; | cmp (x, y)->-1, 0, 1 | ---------------------------------------------------------------------- | Data and other attributes defined here: | _ hash _ = None | _ new _ = <built-in method _ new _ of type object> | T. _ new _ (S ,...) -> a new object with type S, a subtype of TList
The built-in methods can be divided into the following categories based on their functions:
1. Sequence-related methods, such as index, slice, addition, multiplication, and member judgment (these are all described in the sequence of python and are no longer repeated)
2. built-in functions (also summarized in python built-in functions)
3. Common built-in methods.
In my previous article on python, I shared my understanding of the ancestor and compared it to a menu. The list is actually similar to that of the ancestor.
However, yuanzu is like a conservative School, and its menu will not change because the dishes stick to the tradition. However, the list is like an innovative school that attracts customers with endless dishes, so its menus are often modified.
So why do we need to separate the two types? simply use the list. I don't want to change it. Isn't it more convenient?
Although the List supports more operations, the ancestor has the following advantages over the list:
1. Data Security
It is precisely because the ancestor cannot be modified that some misoperation can be prevented. For example, some parameters are very important. When I put them in the list, I may mistakenly modify the parameters, resulting in various errors. However, by putting these important data in the ancestor group, we will be more secure.
2. Higher Performance
Since the list can be modified, you must perform more operations on the memory, and these operations will certainly consume more resources. The ancestor is immutable. Once created in the memory, there will be no extra memory operations. So proceedQueryWhen,Yuanzu is more efficient than the list..
The two features are available based on your needs.
The biggest difference between a list and a parent is that it can be modified, and the core operation to be modified is: add, delete, modify, and query.
I. Add
1.1 L. append (object) -- append object to end
To listLastInsert an element.
A = ['scolia ', 'China'] a. append (123) print aa. append (['new list',]) print aprint a [1] print
Note the following:
1. When the Chinese in the list is stored, the Chinese encoding is stored (the specific encoding is stated at the beginning of the file), and the same is true for the original.
However, when print is used, the two actions are different.
The ancestor can be printed correctly, but the list cannot.
Of course, there is no such problem after the object is obtained using the index.
2. ['new list ',]
When there is only one element like the ancestor, you must add a comma. List is optional.
It does not matter if the list is not written, but the ancestor must be separated by commas when there is only one element !!
3. a [3] [0] Description
This statement fully reflects that an element is an independent object. First, a is a list. We can use the index method to obtain an object a [3], but a [3] is still a list, can I continue to index the retrieved list to retrieve elements.
This is also the principle of the so-called concatenation, which will be analyzed later.
2. L. insert (index, object) -- insert object before index
Insert a new element at a specific index location, and all the original elements are moved to a later position.
a = ['scolia', 123]a.insert(1, 'good')print aa.insert(10, 456)print a
Python puts the excess index value elegantly at the end, which is equivalent to append.
However, if a negative value exceeds the index:
a = ['scolia', 123]a.insert(-10, 456)print a
Will be placed at the beginning, which is also an elegant place for python
3. L. extend (iterable) -- extend list by appending elements from the iterable
Add all the elements of an object that can be iterated one by one to the end of the list. We will describe the iterator later.
Note the following frequently used items:
a = ['scolia']b = ['good',123,456]a.extend(b)print aprint b
You can combine the two lists into one. Of course, B can be the ancestor here, as long as it is an object that can be iterated. Note that the B object itself is not affected.
Ii. Delete
1. L. pop ([index])-> item -- remove and return item at index (default last)
Deletes the elements corresponding to a given index,And return itIf no index is provided, the system deletes the index by default and returns the last one in the list. If the list is empty or the specified index is out of the range, an IndexError is thrown.
Note that the return here means that I can use the variable to undertake the returned element (object ).
a = ['scolia', 'good', 123, 456]b = a.pop()c = a.pop(0)print aprint bprint c
2. L. remove (value) -- remove first occurrence of value.
Given an elementFirstDelete. Note that, unlike the previous one, the deleted object is not returned, and only one empty object is returned, None.
a = ['scolia', 123, 123, 123, 456]print id(a[1]), id(a[2]), id(a[3])b = 123print id(b)a.remove(b)print a
I have already talked about why 123 is the same object in the python sequence. I wrote it here to show that the deletion here is essentially just to delete a reference object, what is reference? I mentioned it in the assignment operation of python.
3. del keyword
In python, The del keyword is used to delete objects. We have said that an element is an object, so we can retrieve the object through indexing or slicing, and then delete it with the del keyword.
a = ['scolia', 456, 123, 123, 123]del a[1]print adel a[1:4]print a
Note: each time you modify the list, the list will be refreshed, which is not obvious when you only modify the list, but when adding or deleting the list, adding or deleting an element refreshes the index value of the entire list.
For example, if a [1] is 456, but it is deleted, the index value of the following element is the first one, so what we get from a [] is the remaining three 123.
3. Change
1. x [I] = y
Modify an element.
a = ['scolia', 'good', 123, 456]a[1] = 'very good'print a
Note: Once the index is exceeded, an error is returned, requiring precise operations.
2. x [I: j] = y
Modify Multiple Elements
When the quantity is correct:
a = ['scolia', 'good', 123, 456]a[1:4] = 'very good', 111, 999print a
When the quantity is incorrect:
a = ['scolia', 'good', 123, 456]b = ['scolia', 'good', 123, 456]a[1:4] = 'very good', 111, 999, 888b[1:4] = 'very good', 111print aprint b
When the number does not match and there is only one:
a = ['scolia', 'good', 123, 456]b = ['scolia', 'good', 123, 456]a[1:4] = 'very good'print ab[1:4] = 111print b
If it is a non-sequential number, an error is reported directly, and the string is split one by one and then filled.
When the new dictionary is modified:
a = ['scolia', 'good', 123, 456]b = ['scolia', 'good', 123, 456]a[1:4] = {'abc':111}b[1:4] = {'abc':111,'cdf':123}print aprint b
The obtained key names are the same as those above, but they are not split when there is only one.
There are many situations here, but these special cases are rarely seen. I just want to list special cases as much as possible,You can't remember it or try it..
3. L. sort (cmp = None, key = None, reverse = False) -- stable sort
Set listFrom small to largeSort. Reverse = True indicates that the data is sorted in ascending order and then flipped over.
a = ['scolia', 123, 123, 456]a.sort()print a
For the comparison of different types of values, I will summarize the comparison operators in the numbers in python.
4. L. reverse () -- reverse
FlipList order. Note that this is not from large to small.
a = ['scolia', 123, 123, 456, 'good']a.reverse()print a
5. L. _ reversed _ () -- return a reverse iterator over the list
Flip the list and generate it into an iteratable object.
a = ['scolia', 123, 123, 456, 'good']print type(a.__reversed__())for x in a: print x
Iteratable objects are generally used for iterative loops. We will talk about them later.
Iv. Query
The indexing, slicing, and member judgment operations can also be considered as queries.
1. L. count (value)-> integer -- return number of occurrences of value
Returns the number of times an element appears in the list (Counter ). It's similar to the one in yuanzuri.
a = ['scolia', 123, 123, 456]print a.count(123)
2. L. index (value, [start, [stop])-> integer -- return first index of value.
Search for the index value for the first occurrence of a given element in the list, which is the same as that in the ancestor. The returned result isIndex Value, Not the number of occurrences.
a = ['scolia', 123, 123, 456]print a.index(123)
3. L. _ sizeof _ () -- size of L in memory, in bytes
The returned list is in the memory size, in bytes.
We will talk about the list first, and we will continue to add it later.