For loops in Python are a bit different than most languages. You may not iterate over some integer and increment as you go. Rather, python uses for loops to iterate over lists or strings (represented as lists). Python also does not use brackets to determine scope, but rather indentation. Example below.
1 2 3 |
>>> x = [1, 2, 3] >>> for value in x: #begin for loop, note the colon >>> print x #part of the loop, indented in |
In some cases, you want to know the where in the list the loop currently is. For this, we can use the enumerate function.
1 2 3 4 5 6 7 |
>>> x = [4, 5, 6] >>> for index, value in enumerate(x): >>> print index 0 1 2 >>> |
Some notes about Python for-loop syntax:
- The for line must end in a colon. This denotes the start of the loop.
- Any line that is indented past the for keyword is PART of the loop. The loop is closed by indenting to the same margin as the original for line.
- No imports are needed for enumerate





