What is list comprehension in Python?
In Python, Lists are those data types surrounded by big brackets [ ] and elements are separated by commas.
A list comprehension is also surrounded by brackets but instead of list of data inside, we enter an expression followed by for loop and if clauses.
List Comprehension Example (for)
To print the square values of the number from 1 to 10, we can use list comprehension for shorter code. The code can be given as:
square_no = [i**2 for i in range(1,11)]
print(square_no)
Output
[1,4,9,16,25,36,49,64,81,100]
And if we include some if statement to print only even square numbers the we modify the list comprehension as:
List Comprehension Example (for & if)
square_no = [i**2 for i in range(1,11) if i%2 == 0]
print(square_no)
Output
[4,16,36,64,100]