Tuesday, May 10, 2011

[python] How to iterate through a list

  • basic iteration 
Iterating through a list in Python is simple using a for in loop.
colours = ["red","green","blue"]

for colour in colours:
    print colour
  • enumerate 
To iterate through the same list using an index we can apply the enumerate() function.
colours = ["red","green","blue"]

for i, colour in enumerate(colours):
    print i, colour

  • Remove elements as you traverse a list
iterate over a copy of the 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: