Looping over a range of numbers
Bad:
for inch [0,1,2,3,4,5]: Print i**2
Good:
for in range (6): Print i**2
Looping over a collection:
Bad:
' Red ','green','blue','yellow ' ] for in range (len (colors)): print colors[i]
Good:
for inch colors: print Colors[i]
Looping backwards
Bad:
colors = ['red','green','blue', ' Yellow ' ] for in range (len (colors) -1,-1,-1): print colors (i)
Good:
colors = ['red','green','blue', ' Yellow ' ] for in reversed (colors): Print color
Looping over a collection and indicies
Bad:
colors = [' red ', ' green ', ' blue ', ' yellow ']for i in range (len (colors)): print I, '--', Colors[i]
Good:
colors = ['red','green','blue', ' Yellow ' ] for in enmerate (colors): print'-- >', Colors[i]
Looping over collections
Bad:
names = ['Raymond','Rachel','Mattew']colors= ['Red','Green','Blue','Yellow']n=min (len (names), Len (colors)) forIinchrange (n):PrintNames[i],' -', Colors[i]
Good:
names = ['Raymond','Rachel','Mattew']colors= ['Red','Green','Blue','Yellow'] forName,colorinchZip (names,colors):PrintName' -', color
Even Beeter. (Izip is processed sequentially, zip is all read-in post-processing, if interrupted in the middle, izip do not need to read all the content)
fromItertoolsImportIzipnames= ['Raymond','Rachel','Mattew']colors= ['Red','Green','Blue','Yellow'] forName,colorinchIzip (names,colors):PrintName' -', color
How to write an elegant Python