for...in

In Python, you can loop over iterable objects:

  1. >>> a = [0, 1, 'hello', 'python']
  2. >>> for i in a:
  3. ... print i
  4. ...
  5. 0
  6. 1
  7. hello
  8. python

One common shortcut is xrange, which generates an iterable range without storing the entire list of elements.

  1. >>> for i in xrange(0, 4):
  2. ... print i
  3. ...
  4. 0
  5. 1
  6. 2
  7. 3

This is equivalent to the C/C++/C#/Java syntax:

  1. for(int i=0; i<4; i=i+1) { print(i); }

Another useful command is enumerate, which counts while looping:

  1. >>> a = [0, 1, 'hello', 'python']
  2. >>> for i, j in enumerate(a):
  3. ... print i, j
  4. ...
  5. 0 0
  6. 1 1
  7. 2 hello
  8. 3 python

There is also a keyword range(a, b, c) that returns a list of integers starting with the value a, incrementing by c, and ending with the last value smaller than b, a defaults to 0 and c defaults to 1. xrange is similar but does not actually generate the list, only an iterator over the list; thus it is better for looping.

You can jump out of a loop using break

  1. >>> for i in [1, 2, 3]:
  2. ... print i
  3. ... break
  4. ...
  5. 1

You can jump to the next loop iteration without executing the entire code block with continue

  1. >>> for i in [1, 2, 3]:
  2. ... print i
  3. ... continue
  4. ... print 'test'
  5. ...
  6. 1
  7. 2
  8. 3