|
Python for experienced programmers |
|
3.4. for loops
Like most other languages, Python has for loops. The only reason you haven't seen them until now is that Python is good at so many other things that you don't need them as often.
Most other languages don't have a powerful list datatype like Python, so you end up doing a lot of manual work, specifying a start, end, and step to define a range of integers or characters or other iteratable entities. But in Python, a for loop simply iterates over a list, the same way list mapping works.
Example 3.5. Introducing the for loop
>>> li = ['a', 'b', 'e']
>>> for s in li:
... print s
a
b
e
>>> print "\n".join(li)
a
b
e
| The syntax for a for loop is similar to list mapping. li is a list, and s will take the value of each element in turn, starting from the first element. |
| Like an if statement or any other indented block, a for loop can have any number of lines of code in it. |
| This is the reason you haven't seen the for loop yet: we haven't needed it yet. It's amazing how often you use for loops in other languages when all you really want is a join or a list mapping. |