T = (1, 2, 3) T[2] = 4 # errorCopy the code
T = T[:2] + (4,) #Copy the code

17. Use simple for loops instead of while or range

When you iterate over all the elements of an ordered object from left to right, a simple for loop (for x in seq 🙂 is easier to write and generally faster to run than counting loops based on while- or range-.

Avoid using range in a for loop unless you absolutely need to: Let Python solve the labeling problem for you. None of the three loop constructs in the following example is problematic, but the first is generally better; In Python, simplicity is Paramount.

S = "lumberjack" for c in S: print c # for I in range(len(S)): print S < len(S) print S[i]; i += 1Copy the code
mylist = mylist.append(X)Copy the code
D = {... } for k in D.keys().sort(): print D[k]Copy the code
Ks = D.keys()
Ks.sort()
for k in Ks: print D[k]Copy the code
I = 1 X = S + I # type errorCopy the code


X = S + STR (I)Copy the code
> > > L = [' grails'] # and reference in the L L can itself > > > L.A. ppend (L #) in the object to create a loop > > > L [' grail, [...]]Copy the code
> > > L = [1, 2, 3] # list of Shared object > > > M = [' X 'L,' Y '] # embed a reference to L > > > M [' X ', [1, 2, 3]. 'Y'] > > > L [1] = 0 # has also changed the M > > > M [' X ', [1, 0, 3], 'Y']Copy the code
> > > L = [1, 2, 3] > > > M = [' X ', L [:], 'Y'] # embed a copy of the L > > > L [1] = 0 # just changed the L, But does not affect M > > > L (1, 0, 3] > > > M [' X ', [1, 2, 3], 'Y']Copy the code
>>> X = 99 >>> def func(): ... Print X # X = 88 # in the entire def treat X as a local variable... >>> func() # error!Copy the code
>>> def saver(x=[]): # Save a list object... X.apend (1) # and each time... Print x # change its value... > > > saver ([2]) # did not use the default values (2, 1] > > > saver (#) to use the default value [1] > > > saver () # each invocation will increase! [1, 1] >>> saver() [1, 1, 1]Copy the code
>>> def saver(x=None): ... If x is None: x = [] # . X.apend (1) # change the new list... print x ... > > > saver ([2]) # didn't use the default value [2, 1] > > > saver () # will not change this time [1] > > > saver () [1]Copy the code

Big data turf