- basic iteration
colours = ["red","green","blue"]
for colour in colours:
print colour
- enumerate
colours = ["red","green","blue"]
for i, colour in enumerate(colours):
print i, colour
- Remove elements as you traverse a list
for c in colors[:]:
if c == 'green':
colors.remove(c)
Hereby colors[:] is a copy (a weird but, sigh, idiomatic way to spell list(colors)) so it doesn't get affected by the .remove calls
No comments:
Post a Comment