For loops

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

3 thoughts on “For loops

  1. Hey there, this post is cool, just that i have a question about it, how would you put your code just to show like just 3 results? Maybe just reduce the range but I’m not sure, What would you do?

    Thank you

    Like

  2. You mean when printing a list? If so, then you would have to type the for loop like this:

    for i in list[0:3]:
    print(i)

    Inside the brackets you are giving the list a range from position 0 to position 2. Therefore the previous for loop will only print out the first 3 values of the list

    Like

Leave a comment