Python List ComprehensionsList comprehensions are Python's solution to the large loops required to do tasks which should be easy. They transform the simple task of getting all the even numbers between zero and one-thousand from:
my_list =  for index in range(1000): if index % 2 == 0: my_list.append(index)to
my_list = [x for x in range(1000) if x % 2 == 0]
The use for list comprehensionsList comprehensions are essentially:
list_name = [expression values filter]Values - A for loop of values to check against the filter Filter - All values go through this. It is an if statement, and the expression is appended to the end of the list when it is true. Expression - Data to append onto the list if Filter is true It's important to note here that the expression could be anything. We could get the squares of all even numbers between zero and one-thousand just as easily:
my_list = [x**2 for x in range(1000) if x % 2 == 0]
Interesting PointsList comprehensions work on strings, and the for loop can loop through any list. The expression can be as complex as you want. The expression is what gets appended, and it can even be another list. Look at this piece of code:
my_list = [[x*y for y in range(1,11) if y % 2 == 0] for x in range(1,11) if x % 2 == 0]This generates a list of lists (which is stored in my_list) where every even number between one and ten is multiplied by every other even number between one and ten.