For more information on concepts covered in this lesson, you can check out:
Using .append() in "for" Loops With Additional Processing
But there are times you can’t use a list comprehension, and that’s when you need to do additional work besides creating the list inside a loop. In that case, you need to go back to using the
.append() method inside a
for loop when building the list. Let’s take a closer look.
00:28 Remember, you’re not only building a list, but doing additional tasks while the list is being populated. Here’s an example. In this case, you want to keep track of how far along the loop is progressing as it computes the square roots. In this example, you want to create a list of square roots from a collection of numbers but you also want to display where in the process each step is at.
After it adds each square root to the list, it wants to display as a percentage how much of the argument
collection has been processed. To do this, it needs a variable to keep track of how much work has been done.
for i, number in enumerate(numbers):. What’s happening here? The
enumerate() function does what you would expect it to. It numbers each of the items in the collection—in this case, it’s also called
numbers—starting with zero. It then returns a collection of tuples, each one unpacked into the variables
number. There’s an excellent Real Python tutorial on
enumerate() if you’d like to learn more about it.
The function displays the number it’s currently at, adds its square root to the
result list, then computes how far it’s progressed through the list, having saved the length of the list to the variable
n before starting the loop.
So there you’ve seen another example of using
.append() inside a
for loop to populate a list, this time when the loop was supposed to do additional processing and you weren’t able to use a list comprehension.
Become a Member to join the conversation.