List comprehensions are a concise way to create lists. They are used to create a new list by iterating over another list.
It consists of square brackets containing an expression followed by the “for” keyword. The result will be a list whose results match the expression.
The basic syntax is :
newlist = [output_expression(x) for x in oldlist if conditional(x)]
The above syntax is explained through the illustration below:
The list comprehension basically consists of four parameters.
The following code creates a list containing the square of numbers:
l1=[] #declare an empty listl1=[x*x for x in [0, 1, 2, 3]] #store the result of list comprehension in l1print (l1)#print the list
The following code uses a predicate expression and stores only the square of those numbers in the list which is divisible by 2:
l1=[] #declare an empty listl1=[x*x for x in [0, 1, 2, 3] if (x%2==0)] #store the result of list comprehension in l1print (l1)#print the list
Free Resources