For loop in Python

The For loop in Python has some different features than other programming languages. I leave you what I am learning to get the most out of one of the most used loops.

In Python it is intended to iterate through an iterable object, be it a list, an object, or another element.

The following structure is

h2=[ 'Valencia', 'Castellón', 'Alicante']

for j in h2:

Here h2 is an iterable element for example a list h2=[ 'Valencia', 'Castellón', 'Alicante']. The loop will have 3 iterations, in the first j=Valencia in the second the variable j=Castellón.

And with this we can define the instructions we want, always remembering the indentation, something essential in Python and that many people ignore, getting errors in the code.

Iterate for loop an exact number of times.

If we want it to repeat a certain number of times as we can do in C++ we will have to use range(). To iterate 10 times we would use a

for element in Range(9):

We put 9 and not 10 because Range starts from 0, so from 0 to 9 there are 10 iterations or turns of the loop.

Knowing Range() allows us, instead of putting a number inside, to put a variable, so we will have much more control.

var = 10
for element in Range(var):

The Range function has many options, I will talk about it in another post, so as not to mix the content and develop it as much as possible.

Much more can be done to control the flow of the for loop.

Break and Continue Statements

There are 2 very useful features that allow us to make a for loop very functional, fon the break and the continue. They are usually used with conditionals, if, checking if something is true.

They work in other loops, and there is another interesting statement that is pass, which is a statement that is executed but does nothing and is ideal for when we want to define a structure that requires commands but we want to put them later (comments are not useful for this)


With break we can exit the loop at any time. As you imagine very useful. It is true that there are other structures like While,

numeros = [1, 2, 4, 3, 5, 8, 6]
for n in numeros:
    if n == 3:
    print('No se encontró el número 3')


It makes us go to the next element in the loop.

numeros = [1, 2, 4, 3, 5, 8, 6]
for n in numeros:
    if n == 3:
    print('No se encontró el número 3')


There is a structure derived from For, which is for … else

datos = [1, 2, 3, 4, 5]
for n in datos:
    if n == 2:
    print('No hay 2')

This structure arose after they saw that it was necessary and that many people were using alternative ways to achieve this. Thus, they help people and get a more readable code

for_in iterable

I have seen this in some programs although I have never used it.

When we are iterating an object, list, dictionary, etc, but the content of those elements does not interest us, we can indicate it with _

An example:

We want to count the elements of a list but we don't care what it contains, we just want its length.

h2=[ 'Valencia', 'Castellón', 'Alicante']
count = 0
for _ in h2:
    cont += 1

In many sites they recommend not to abuse this practice. I really don't know the advantages it presents, is it faster?

looping backwards

backward for loop. To iterate from the end to the beginning

It uses the reversed() function introduced in python 3

h2=[ 'Valencia', 'Castellón', 'Alicante']

for j in reversed(h2):
    print (j)

Looping with two indices, value of the iterable and index

With enumerate() we can work with the indices of a collection. Because many times, in addition to the value of the iterable object itself, we are interested in its index.

h2=[ 'Valencia', 'Castellón', 'Alicante']

for j, h in enumerate(h2):
    print j, '-->', h2[i] 

Iterating over 2 lists

Another very interesting option is zip() that will make our work easier and will make our code simpler and more readable.

h2=[ 'Valencia', 'Castellón', 'Alicante']
cod=[100, 200, 300]

for j, h in zip(h2, cod):
    print h2, '-->', cod 

In Python 2.x izip() was used to enhance this function, but in Python 3 izip is zip()

Looping in sorted order

Iterate in order by the value of the object instead of by its index. sorted() is used

colors = ['rojo', 'amarillo', 'verde']

for color in sorted(colors):
    print color

And if we want to do it backwards

colors = ['rojo', 'amarillo', 'verde']

for color in sorted(colors, reverse=True):
    print color

Custom sort order

colors = ['rojo', 'amarillo', 'verde']

for color in sorted(colors, key=len):
    print color

Sentinel Value in for loop

The sentinel value is a value that causes the loop to end. It is usually presented in a while loop, but Raymond Hettinger shows us how to use it with a for, which is faster

blocks = []
for block in iter(partial(, 32), ''):
    print (block)

Traverse dictionaries with for

Dictionaries are essential tools for expressing relationships and making groupings.

You can go through the dictionary in a traditional way with for, but that won't return all the information, we won't be able to work with values ​​and indices like that, if we don't start adding counters and other elements.

d = {'casa': 'azul', 'coche': 'rojo', 'hombre': 'verde'}

for k in d.keys():
    if k.startswith('r'):
        del d[k]

In this way, in addition to seeing the elements, we can modify the dictionary by changing elements or deleting them, at the same time that the for loop is iterated.

d.keys() calls the arguments and makes a copy that it stores in a list that we can modify.

To get indexes and values ​​instead of something traditional and that is the first thing that comes to mind for those of us who start programming

for k in d:
    print k, '-->', d[k]

We will use this much faster option

for k, v in d.items():
    print k, '-->', v

iteritems() than items()

Talk about Loops in Python by Raymond Hettinger

It is an old but very illustrative video, where in the first 20 minutes Raymond Hettinger teaches us the different possibilities of loops in Python and gives us examples of how they transform structures widely used by people into functions, to make the loop more readable and simpler. code.

Leave a comment