Python: For Loop or List Compilation?

For loop or listcomp, which one should I use? Python programmer might find himself asking this question sometimes. If you dont know what the list compilation (listcomp) is, dont worry, you`ll learn that now.

Lets say we want to create an array of numbers 1 to 20, we can do it in for loop like this:

                    >>> numbers = []
                    >>> for x in range(0, 20):
                    ...     numbers.append(x)
                    ...
                    >>> numbers
                    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
                

Or we can do a listcomp:

                    >>> numbers = [x for x in range(0, 20)]
                    >>> numbers
                    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
                

Listcomp is quiet amazing, isn`t it? Now when do we use it, and when not? Simple. Use it whenever you want to create a list/array. It allows for much more readable and cleaner way of building a list, what makes your code more readable and cleaner too.. If you however need to perform some processing as part of creating list, than stick with the for loop.

That`s all for listcomps vs iteration.

19/11/2017