for...in
In Python, you can loop over iterable objects:
>>> a = [0, 1, 'hello', 'python']
>>> for i in a:
... print i
...
0
1
hello
python
One common shortcut is xrange
, which generates an iterable range without storing the entire list of elements.
>>> for i in xrange(0, 4):
... print i
...
0
1
2
3
This is equivalent to the C/C++/C#/Java syntax:
for(int i=0; i<4; i=i+1) { print(i); }
Another useful command is enumerate
, which counts while looping:
>>> a = [0, 1, 'hello', 'python']
>>> for i, j in enumerate(a):
... print i, j
...
0 0
1 1
2 hello
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
>>> for i in [1, 2, 3]:
... print i
... break
...
1
You can jump to the next loop iteration without executing the entire code block with continue
>>> for i in [1, 2, 3]:
... print i
... continue
... print 'test'
...
1
2
3