Populating Lists From Scratch in "for" Loops

00:00 In this lesson, you’ll see one of the most common uses of the .append() method, which is populating a list from within a loop.

00:09 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.

00:28 But let’s start with the for loop. To populate a list this way, you create a for loop which will iterate over the way you want to create each element.

00:38 Then, in the same loop, call .append() to add that element to the existing list.

00:45 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.

01:14 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 numbers.

01:36 You need a variable to refer to each element in that collection. Here, it’s called number. What do you want each list element to look like?

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.

02:02 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.

02:20 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 4 is 2 will be appended to result, and then 3, and then so on.

02:41 And the result is then displayed. To see this, let’s run this script in a terminal window.

02:51 It’s called show_square_roots1.py. So we run this,

02:59 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.

03:14 It’s called a list comprehension, and you’ll see that next.

Become a Member to join the conversation.