For loops

--Originally published at Programming

Iterate over a sequence of items

Unlike other programming languages like C or java, the for loop doesn’t always iterate over an arithmetic progression of numbers. What Python does in for statements is that it iterates over the items of a sequence (a list or a String). Let’s take a look at an example.

1.png

We have a list that contains 4 different strings so in order to print all of them it is necessary to create a for loop, where the variable i is going to iterate over all the elements inside the list list. So the first time the loop runs, the variable i is going to be the first element of the list and is going to print the string “ham”. The second time the loop runs it will print the string “Cheese” and so forth until it reaches the last element of the list.

Iterate over a sequence of numbers

When you need to iterate over a sequence of numbers, you can use the built-in function range(). The parameter inside range() is the number of times you will be iterating. If you type range(10) the variable will iterate from 0 to 9. If you type range (1,10) it’ll iterate from 1 to 9 and if you type range(0,11,2) the variable will iterate from 0 to 10 with steps of 2.

2.png

3.png