The for Loop
Explore how to use the Python for loop to iterate over sequences like ranges, lists, and dictionaries. Understand the range function's parameters for customizing iterations and learn how to combine loops with conditional statements such as using the modulus operator to filter values during iteration.
We'll cover the following...
As mentioned above, you use a loop when you want to iterate over something n number of times. It’s a little easier to understand if we see an example. Let’s use Python’s builtin range function. The range function will create a list that is n in length. In Python 2.x, there is actually another function called xrange that is a number generator and isn’t as resource intensive as range. They basically changed xrange into range in Python 3. Here is an example:
As you can see, the range function above took an integer and returned a range object. The range function also accepts a beginning value, an end value and a step value. Here are two more examples: ...