There's nothing difficult about this piece, so be careful.
L =[]n= 1 whileN <= 99: L.append (n) n= n + 2Print(L)#but in Python, the more code is better, the less the better. The more complex the code is, the better it is, but the simpler the better. #based on this idea, we introduce the very useful advanced features in Python, the functionality that 1 lines of code can implement, and never write 5 lines of code. Always keep in mind that the less code you have, the more efficient your development. L= ['Michael','Sarah','Tracy','Bob','Jack']#methods for taking the first three elementsPrint([L[0], l[1], l[2]])#[' Michael ', ' Sarah ', ' Tracy ']#Loop method Take elementR =[]n= 3 forIinchrange (N): R.append (L[i])Print(R)#[' Michael ', ' Sarah ', ' Tracy ']#It is cumbersome to use loops for operations that often take a specified index range, so Python provides a slice (Slice) operator that can greatly simplify this operation. #corresponding to the above problem, take the first 3 elements, a line of code to complete the slice:Print(L[0:3])#[' Michael ', ' Sarah ', ' Tracy ']#L[0:3] Indicates that the fetch starts at index 0 until index 3, but does not include index 3. That is, index 0,1,2, which is exactly 3 elements. #If the first index is 0, you can also omit:Print(L[:3])#[' Michael ', ' Sarah ', ' Tracy ']#slice backwards.Print(l[-2:])#2 to 0 does not include 0 (of course, it is not possible to include 0, the index of the first element of the countdown is-1, notice that 0 is not written, otherwise it will output [])Print(L[-2:-1])#2 to-1 does not include-1, that is, the second-lowest element#Remember that the index of the first element of the countdown is-1.!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#slicing operations are useful. Let's start by creating a 0-99 series:L = List (range (100))Print(L)#you can easily remove a segment of a sequence by slicing it. such as the first 10 numbers:Print(l[:10])#after 10 numbersPrint(l[-10:])#number of first 11-20Print(l[10:20])#first 10 numbers, each of two fetch one:Print(L[:10:2])#all numbers, take one per fivePrint(L[::5])#don't even write anything, just write [:] to copy a list as it is:Print(l[:])Print('---------------------')#tuple is also a list, the only difference is that the tuple is immutable. Therefore, a tuple can also be used for slicing operations, but the result of the operation is still a tuple:T = (0, 1, 2, 3, 4, 5) [: 3]Print(t)#(0, 1, 2)#in many programming languages, there are a number of different interception functions for strings (for example, substring), which is actually intended to be a string slice. Python does not have an intercept function for a string, it can be done simply by slicing one operation.
Python slicing exercises