List comprehensions are a feature of Python that give us a clean, concise way to create lists.
A common use case would be when you need to create a list where each element is the result of some operations applied to each member of another sequence or iterable object.
The syntax for a list comprehension is pretty similar to creating a list the traditional way. It consists of square brackets [] containing an expression followed by a for clause, then zero or more if clauses.
Let's go back to the example we looked at previously, where we needed to calculate the squares of numbers. To calculate the squares of all numbers from one to ten using a for loop, we could do the following:
Python 3.6.1 (default, Dec 2015, 13:05:11) [GCC 4.8.2] on linux for num in range(1,11): print(num**2) 1 4 9 16 25 36 49 64 81 100
The same can be achieved by using list comprehensions, as follows:
Python 3.6.1 (default, Dec 2015, 13:05:11) [GCC 4.8.2] on linux squares = [num**2 for num...