Loops

Loops are a way to repeatedly execute some code. Here's an example:

The for loop specifies

You use the word "in" to link them together.

The object to the right of the "in" can be any object that supports iteration. Basically, if it can be thought of as a group of things, you can probably loop over it. In addition to lists, we can iterate over the elements of a tuple:

You can even loop through each character in a string:

range()

range() is a function that returns a sequence of numbers. It turns out to be very useful for writing loops.

For example, if we want to repeat some action 5 times:

while loops

The other type of loop in Python is a while loop, which iterates until some condition is met:

The argument of the while loop is evaluated as a boolean statement, and the loop is executed until the statement evaluates to False.

List comprehensions

List comprehensions are one of Python's most beloved and unique features. The easiest way to understand them is probably to just look at a few examples:

Here's how we would do the same thing without a list comprehension:

We can also add an if condition:

(If you're familiar with SQL, you might think of this as being like a "WHERE" clause)

Here's an example of filtering with an if condition and applying some transformation to the loop variable:

People usually write these on a single line, but you might find the structure clearer when it's split up over 3 lines:

(Continuing the SQL analogy, you could think of these three lines as SELECT, FROM, and WHERE)

The expression on the left doesn't technically have to involve the loop variable (though it'd be pretty unusual for it not to). What do you think the expression below will evaluate to? Press the 'output' button to check.

List comprehensions combined with functions like min, max, and sum can lead to impressive one-line solutions for problems that would otherwise require several lines of code.

For example, compare the following two cells of code that do the same thing.

Here's a solution using a list comprehension:

Much better, right?

Well if all we care about is minimizing the length of our code, this third solution is better still!

Which of these solutions is the "best" is entirely subjective. Solving a problem with less code is always nice, but it's worth keeping in mind the following lines from The Zen of Python:

Readability counts.
Explicit is better than implicit.

So, use these tools to make compact readable programs. But when you have to choose, favor code that is easy for others to understand.

Your Turn

You know the deal at this point. We have some fun coding challenges for you. This next set of coding problems is shorter, so try it now.


Have questions or comments? Visit the Learn Discussion forum to chat with other Learners.