Python 3 – List comprehensions by examples

In the post Using lists with Python 3 I explained something about lists in Python, however, since Python is very slow in FOR-LOOPS, to generate lists Python supports a concept named “list comprehensions“. “list comprehensions” can be used to construct lists in a very natural and easy way, like a mathematician is used to do.

For example:

The above piece of code generates this list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], using list comprehensions the same list can be generated with the following line of code:

one line of code versus 3 lines of code….

List comprehensions advantages:

  • Compact notation:
    From the example above we have already seen the first advantage, we could write less code. And, as any SW developer knows “less code means less bugs”
  • Speed:
    Another effect on using LC is to have better performances, for example imagine you have a square matrix (10000×10000) and you want to flatten this matrix. Using for-loop

to get the time spent I use the time_fun decorator explained at ()

And the results will be:

You can find the full source code for this example at ()

Let’s go ahead with other examples:

will generate a list containing the squares of the first 10 integers

Imagine you want to create a new list containing all elements of list_comp_2 that are even, with for-loop code:

And the results will be:

the same list using list comprehensions

And the results will be:

all elements contained in both LIST_COMP_2 and NEWLIST_COMP that are even:

And the results will be:

the same list using for-loop

And the results will be:

Really great concept.

You can find full source code for this blog post at my github at lists_and_comprehension.py

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *