Now that we have the tools to make some interesting data structures, we'll look
at Python's other type of loop construct, the for
-loop. The for
-loops in Python correspond to what are called for-each
loops in many other programming languages. They request items one-by-one from a collection – or more strictly from an iterable series (but more of that later) – and assign them in turn to the a variable we specify. Let's create a list collection, and use a for
-loop to iterate over it, remembering to indent the code within the for
-loop by four spaces:
>>> cities = ["London", "New York", "Paris", "Oslo", "Helsinki"] >>> for city in cities: ... print(city) ... London New York Paris Oslo Helsinki
So iterating over a list yields the items one-by-one. If you iterate over a dictionary, you get just the keys in seemingly random order, which can then be used within the for
-loop body to retrieve the corresponding values. Let's define a...