Sitemap
Daniela Garcia

Daniela Garcia

Using the for loop with Python lists

4 min readFeb 21, 2024

For loops are invaluable tools in programming when tasks need to be repeated multiple times, particularly when working with lists in Python. The syntax is straightforward:

For example, consider a list of fruits: apples, peaches, and pears.

Printing them out individually requires iterating through the list using a for loop:

Each iteration assigns a single fruit to the variable `fruit`, allowing us to execute the same line of code for each item in the list.

You can include additional operations within the loop, as long as they are indented. For instance:

Indentation is crucial; without it, the additional operation won’t be considered part of the loop.

For Loop with `range()` Function

When dealing with specific ranges of numbers, the `range()` function combined with a for loop is incredibly useful. Its syntax is:

For example, to print numbers from 1 to 9:

Note that the end value is exclusive. To include it, use the value one greater.

Get Daniela Garcia’s stories in your inbox

Join Medium for free to get updates from this writer.

If you want to print specific numbers within the range, specify the step size. For instance, to print every third number:

This prints every third number within the range.

Calculating the Sum of Numbers

Here’s how you can calculate the sum of all numbers from 1 to 100 using a for loop:

1. Initialization: Set up a variable named ‘total’ and initialize it to 0. This variable will store the running sum of numbers.

2.For Loop: Start a ‘for’ loop that iterates over a range of numbers from 1 to 100 (inclusive). The `range(1, 101)` generates a sequence of numbers starting from 1 and ending at 100.

3. Summation: Within the loop, add the current value of `number` to the `total` in each iteration. For example, in the first iteration, `total` becomes 1; in the second iteration, `total` becomes 1 + 2 = 3, and so on. This process continues until the loop reaches 100.

4. Print Result: After the loop has finished iterating over all the numbers, print the total sum of the numbers, which is stored in the variable `total`.

To illustrate the process easily

[0 + 1 + 2 + 3 + \ldots + 98 + 99 + 100 = 5050]

So, when you run this code, it should print ‘5050’ as the output, which is the sum of all numbers from 1 to 100.

--

--