A python idiom that creates a shortcut for a for loop. It returns a copy of a list with every element transformed via an expression. Functional programmers refer to this as a mapping function.
[function for item in list]
Example:
>>> words = "This is a list of words in a sentance.".split()
>>> [len(word) for word in words] #print out the Len of each word in the above sentence.
[4, 2, 1, 4, 2, 5, 2, 1, 9]
This can also be done using the map function
>>> words = "This is a list of words in a sentance.".split()
>>> list(map(len, words))
[4, 2, 1, 4, 2, 5, 2, 1, 9]
>>> from math import factorial
>>> f = [len(str(factorial(x))) for x in range(20)]
>>> f
[1, 1, 1, 1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 18]
results=[]
for var in sequence:
results.append(Express) # where Express involves var
results = [ expr for var in sequence ]
results = [ expr for var in sequence if expr ]
>>> numbers = [1,2,3,4,5,6,7,8,9,10]
>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> squared = [x**2 for x in numbers ]
>>> squared
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> evens = [ x *2 for x in range (20)]
>>> evens
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]
>>> fruits
['watermelon', 'Apple', 'mango', 'KIWI', 'aprcot', 'LEMON', 'guava']
>>> ufruits = [fruit.upper() for fruit in fruits]
>>> ufruits
['WATERMELON', 'APPLE', 'MANGO', 'KIWI', 'APRCOT', 'LEMON', 'GUAVA']
>>> values =[ 2,42,18,92,'boom',['a','b','c']]
>>> doubles = [v*2 for v in values]
>>> doubles
[4, 84, 36, 184, 'boomboom', ['a', 'b', 'c', 'a', 'b', 'c']]