Extensions
Break, Continue, Enumerate, Strings as Lists, List comprehension
Break and Continue
Sometimes we want to exit a for/while loop before the defining condition is met, or skip some of the iteration steps. Break and Continue statements provide this functionality respectively - Note it is not good practice to use these unnecessarily, as you can usually just define the loop condition differently.
Break
If we want to exit a loop prematurely, we can use the break statement.
For an actual usage example, suppose we want to find a prime number greater than 9000, but less than 10000 (not knowing if there is one in this range):
Continue
Continue allows us to skip iteration steps inside a loop. This might be helpful if we have a complicated for loop which shouldn't carry out its usual operation in a certain case.
For example, we could print the even numbers < 10:
Note: This is not actually a sensible use of continue, as there are far better ways of printing even numbers in a range (for example, x2 every element in range/2).
Enumerate
Sometimes we want to iterate through a list, accessing its elements but also keeping track of the corresponding index. Whilst we could use a counter variable to do this manually, Python's built-in enumerate() function provides and elegant way of doing this:
Strings as lists of characters
Some of you may have noticed that we can use the "in" function on strings as well as lists:
Equivalent to
For our purposes, we can think of strings as lists of characters, and manipulate them as we would lists - slicing and all!
Here's a simple example demonstrating reverse iteration through a string:
And another example showing some contrived list slicing:
Last updated