List comprehensions

List Comprehensions

One particularly nifty feature of the Python language are list comprehensions. List comprehensions provide a really concise way of constructing lists. 

One, perfectly acceptable way to construct a new list in Python would be as follows:

x = range(10)
myList = [] # this is an empty list

for i in x:

List comprehensions give us a way to achieve the same result with far few lines of code, like so:

x = range(10)
myList = [i for i in x]

The use of a list comprehension in this simple example removes the need to (a) create an empty list object and (b) construct a for loop block to iterate over the object whose items we are a seeking to add to the empty list.