Populating Lists From Scratch in "for" Loops
A very common task in Python—and other programming languages, for that matter—is to create a list iteratively. Here, you’ll see how to do that using
.append() inside a
for loop. And in the next lesson, you’ll see how that’s done with something called a list comprehension.
Here’s one example, creating a list of square roots of a collection of values. This function is going to operate by taking a list as an argument saved to the parameter
numbers containing the numbers you want to take the square root of. Note that since we are going to be using a square root function, you should import Python’s
math module, which has that and many other useful mathematical functions.
Before the loop begins, you create an empty list and save that to a variable. This is the list you are going to populate one element at a time each time the following
for loop is executed. In this case, you’re going to find the numbers to take the square root of in the collection provided in the parameter
01:46 Well, here, it should be the square root of the number you’re currently looking at, so you compute that number and append it to the existing list. You do this for every number provided in the argument.
Then, outside the
for loop after it’s completed—and it’s very important to make sure this is outside the loop and not in it—you return the populated list. As an example, let’s see how this will perform with a list of the first nine perfect squares.
Each one, one at a time, will have its square root taken, and then that value will be appended to the end of the list called
result. So, first,
1 will be put in the list, then the square root of
2 will be appended to
result, and then
3, and then so on.
and here, you can see the numbers in that list generated by the
.append() method being used inside the
for loop. This is a very common operation—so common that Python has a different syntax to perform the same action.
Become a Member to join the conversation.