A journey of a thousand miles begins with a single step. Want to become the eye of a pair of insight everything, still must learn basic skill solidly first. Today, Ben walks you through the Python list. Consider the old and learn the new.
Of course, think outside the box as well, because some seemingly innocuous language conventions, such as why an array index starts at 0, may have a history behind them. Know what it is, and know why, meow, meow, meow
Finally, in addition to the basic knowledge, it is necessary to explore further steps, such as learning generator expressions, so that we can not only have a solid grasp of the basics, but also be able to understand them thoroughly and obtain a more comprehensive cognitive upgrade.
How do Python lists look?
A list is an ordered collection of elements that can be added, found, and removed at any time.
Lists can add elements of different data types: numbers, strings, lists, tuples, and so on.
A list traverses all elements through an ordered index. The index is [0,n-1], and the index is [-1, -n], where n is the length of the list.
Lists can be empty lists with no elements, or they can contain a very large number of elements (if memory size allows).
List_a = [] # empty list, namely the len (list_a) = = 0 list_b = [10, 2018, '2018-10-1', 'hi', 1, 2], (33, 44)] # list_b length is 5, Len (list_b) == 5list_b[0] == list_b[-5] == 2018lits_b[3] == list_b[-2] == ['hi', 1, 2] lits_b[4] == list_b[-1] == (33, 44)
Copy the code
How do you manipulate lists in Python?
1) Create a list:
Wrap elements in brackets [], separated by commas.
Using the list() method, the transformation generates a list.
List generation/list parsing/list derivation, generate list.
list_a = [1, 2, 3]list_b = list("abc") # list_b == ['a', 'b', 'c']list_c = list((4, 5, 6)) # list_c == [4, 5, 6]list_d = [i for i in list_a] # list_d == [1, 2, 3]list_e = [I *j for I,j in] # list_e == [4,5,6,10,12, 15,18]list_f = [I *j for I,j in # list_f == [4, 10, 18] # list_g == [I for I in list_A if I %2 == 0] # Range (start, stop[, step])list_h = list(range(3)) # list_h == list(range(3,7)) # list_h == list(range(3,7)) # list_h == list(range(3,7)) # list_h == list(3, 4, 5) 6] list_j = list (range (3,9,2)) # list_j = = [3, 5, 7] # to find 100 positive integers can be divided exactly by 3 within list_k = list (range (3100, 3)) # list_k = = [3, 6, 9,..., 96, 99]
Copy the code
2) Expanded list:
Use the append() method to add a single new element to the end of the list.
Use the insert() method to add an element at the specified position in the list.
The + operator concatenates the two lists into a new list.
Concatenate one list into another using the extend() method.
# below add 2 elements respectively list_a = [] list_a. Append (' happy ') # list_a = = [' happy '] list_a. Insert (0, 'very') # list_a = = [' very ', 'happy'] # the following two types of expanded list list_1 = [' I 'and' am '] list_2 = [' very ', 'happy'] list_3 = list_1 + list_2 # new list list_3 = = [' I 'and' am ', 'very', 'happy'] list_1. The extend (list_2) original list # 1, list_1 = = [' I 'and' am 'and' very ', 'happy']
Copy the code
3) Delete list and Destroy List:
Delete the element at index m with the del list[m] statement.
Remove the element (the first match) with the specified value using the remove() method.
With the pop() method, extract and delete the single element at the end of the list.
Using the pop(m) method, fetch and delete the element with index m.
Using the clear() method, clear the list of elements. (Glass still standing, empty)
Using the del list statement, destroy the entire list. (There is no more glass or water.)
# the following four kinds of way to delete list elements list_1 = list_2 = list_3 = list_4 = [' I ', 'am', 'very', 'happy'] del list_1 [0] # list_1 = = [' am 'and' very ', 'happy']list_2.remove('I') # list_2 == ['am', 'very', 'happy']list_3.pop() # list_3 == ['I', 'am', 'very'] list_4. Pop (0) # list_4 = = [' am 'and' very ', 'happy'] # to empty and destroy list_a = [1, 2, 3] list_b = [1, 2, 3]list_b. Clear () # list_b == []del list_a #
Copy the code
4) List section:
Basic meaning: starting from the ith bit index, take the right to the last n bits of the element, filter by m interval
Basic format: [I: I +n: m]; I is the initial index value of the slice, which can be omitted if it is the first place in the list. I +n is the end position of the slice, which can be omitted if it is the end of the list. M may not be provided. The default value is 1 and cannot be 0. When m is negative, the list is flipped. Note: these values can be greater than the list length and are not reported out of bounds.
Li = [1, 4, 5, 6, 7, 9, 11, 14, 16] Where X > = len li (li) [0: X] = = li [0:] = = li: [X] = = li [:] = = li [: :] = = li / - X: X = = li [-x:] li [1] = = [4, 7] from # 1, Take 5 - one element li [1:5:2] = = [4, 6] # from 1, 5 - one element, press 2 filter between li [1:] = = [16] # take the first element from bottom li [- 4: - 2] = = [9, 11] # from the fourth from bottom, Take - 2 - (4) = 2 element li [: - 2] = = li [- len (li) : - 2] = = #,4,5,6,7,9,11 [1] from the beginning, take - 2 - (- len (li)) = # 7 elements note list first, To intercept li] [: : - 1 = =,14,11,9,7,6,5,4,1 [16] # flip the entire list li [: : - 2] = =,11,7,5,1 [16] # flip the entire list, Then press 2 filter between li [: - 5:1] = =,14,11,9 [16] # flip the entire list, take - 5 - (- len (li)) = 4 elements li [: - 5-3] = = [16, 9] # flip the entire list, take - 5 - (- len (li)) = 4 elements, [::0] [ValueError: Slice step cannot be zero] [::0]
Copy the code
5) Other operations:
Use len() to count all elements.
The count() method counts the number of elements with a specified value.
Using the Max () method, count the maximum number of elements (elements of the same type; Number types compare directly, other types compare id)
Using the min() method, count the minimum values in the elements (elements of the same type; Number types compare directly, other types compare id)
Finds the index position (the first match) of the element with the specified value using the index() method.
Use the reverse() method to reverse the elements in the list.
Using the copy() method, shallow copy and generate a new list.
Using the deepcopy() method, make a deepcopy and generate a new list.
Sort on the original list using the sort() method.
Use the sorted() method to sort the elements of the original list based on the new list.
list_1 = [2018, 10, '2018-10-1', ['hi', 1, 2], (33, 44)] len (list_1) = = 5 list_1. Count ten (10) = = 1 # element for 1 list_1. The number of index of element (10) = = 1 # 10 indexes for 1 list_1. Reverse () # list_1 = = [(33, 44), [' hi ', 1, 2], '2018-10-1', 10, 2018] # is shallow and deep copy import copylist_a = [10, 2018, '2018-10-1', 'hi', 1, 2], [33, 44)]list_b = ['hi', 1, 2]list_c = list_a.copy() # list_c == [2018, 10, '2018-10-1', ['hi', 1, 2], (33, 44)]list_d = copy.deepcopy(list_a) # list_d == [2018, 10, '2018-10-1', ['hi', 1, 2], (33, # 44)] to change the original list of the variable object elements list_a [3]. The append (' new ') # list_a = = [10, 2018, '2018-10-1', [' hi ', 1, 2, 'new'], (33, 44)] # variable object of shallow copy will changes over the original list list_c = = [10, 2018, '2018-10-1', [' hi ', 1, 2, 'new'], (33, List_d == [2018, 10, '2018-10-1', ['hi', 1, 2], Sorted ()list_1 = 2 = [2,1,4,6,5,3]list_1.sort() List_1 = = [6] list_3 = sorted (list_2) # original list remains the same: list_2 = =,1,4,6,5,3 [2]; List_3 = = [6]
Copy the code
Why does the Python list index start at 0?
Authoritative explanation from Guido van Rossum: Why Python uses 0-Based Indexing
Summary: Indexing starts at 0 and slicing is elegant.
The essence of translation is as follows:
One reason I decided to use the 0-based indexing approach in Python was the Slice notation.
Let’s look at slicing first. Probably the most common usage is “take the first n-bit element” or “take the last n-bit element from the i-th index” (the former usage is actually a special use of the starting bit of I ==). It would be very elegant if these two usages could be implemented without ugly +1 or -1 in expressions.
Using 0-based indexing, half-open interval slicing, and default matching intervals (which Python eventually adopted), the slicing syntax for the above two cases becomes very nice: a[:n] and a[I: I +n], the former being an abbreviation of a[0:n].
If the 1-based indexing method is used, then to make a[:n] express the meaning of “take the first n elements”, you can either use closed interval slicing syntax, or use slicing start bit and slicing length as slicing parameters in the slicing syntax. The half-open interval slicing syntax becomes inelegant when combined with 1-based indexing. With closed interval slicing, you write the expression a[I: I +n-1] in order to get the last n elements from the i-th index.
…
Especially when two slice operation positions are adjacent, the end index value of the first slice operation is the starting index value of the second slice, which is too beautiful to be discarded. For example, if you want to cut a string into three parts at positions I and j, the expressions for the three parts will be a[: I], a[I :j], and a[j:].
Indexes for other programming languages?
Index programming languages starting from 0: C, C++, Python, Java, PHP, Ruby, Javascript…
Index of programming languages starting from 1: ABC, Matlab, VB, easy languages, most shell languages…
Programming languages that index from other values: Pascal, Lua…
There are also data that represent sequential structures such as days and months, which the various programming languages fall into different camps.
What are their considerations?
Starting from 0 C: index, can greatly improve memory addressing computing efficiency, detailed analysis of the reference “[why start from 0 C language array element subscript] (https://blog.csdn.net/bufanq/article/details/51330197)”
Most shell languages: Most of them start at one, Source of reference [stackexchange this q&a] (HTTP: / / https://unix.stackexchange.com/questions/252368/is-there-a-reason-why-the-first-element-of-a-zsh -array-is-indexed-by-1-instead-o)
Pascal, Lua: default starting from 1, but support to change the starting index value, the reason is said to be more friendly for non-professional developers, source of reference [this article zhihu q&a] (https://www.zhihu.com/question/19675689/answer/19174752)
The reasons listed above are the most prudent and honorable explanations, and the topic should end there, because the question “what is the best index to start with?” is no less damaging than the question “which programming language is best?”……
Nice and elegant ending: generator expressions
List type is a kind of elegant beautiful things, but it has a fatal flaw: it once loaded into memory, put all the elements when the list is too long, it will occupy too much memory resources, and we usually need to use a few elements, so the unused elements occupied most of the memory, become unnecessary spending.
A generator is a more advanced and elegant thing that uses the principle of “lazy loading” and does not generate a complete list, but generates elements iteratively, instantaneously, and on demand, which not only saves a lot of memory, but, in theory, can produce an infinite list!
Most generators are implemented as functions; however, instead of returning a value, they yield a value and suspend the program. Then, an element is generated and returned immediately through the next() method, or all elements are generated and returned one by one through the for loop.
Next () is inefficient and will raise StopIteration when it is called out of bounds. The for loop will automatically catch this exception and stop calling, so it is better to use it.
Def fibon(n):a = b = 1for I in range(n):yield a # use the yielda, b = b, a + b# calculate the first 1000000 numbers by using the next() function, G = fibon(1000000)next(g) # 1next(g) # 1next(g) # 2next(g) # 3next(g) # 5 For x in fibon(1000000):print(x)
Copy the code
Generator expressions are very similar to list generators, except that [] is changed to (), but the underlying principle is quite different.
L = [x*2 for x in range(5)] g = (x*2 for x in range(5)) <type 'generator'>print(l) # <generator object at 0x000002173F0EBC50>next(g) # 0next(g) # 2next(g) # 4next(g) # 6next(g) # 8next(g) # Traceback (most recent call last): .... StopIterationfor x in g:print(x, end= "") #
Copy the code