List Comprehension in Python Example
Here is an example of using list comprehension to find the square of the number in Python.
Python
numbers = [ 1 , 2 , 3 , 4 , 5 ] squared = [x * * 2 for x in numbers] print (squared) |
Output
[1, 4, 9, 16, 25]
Iteration with List Comprehension
In this example, we are assigning 1, 2, and 3 to the list and we are printing the list using List Comprehension.
Python
# Using list comprehension to iterate through loop List = [character for character in [ 1 , 2 , 3 ]] # Displaying list print ( List ) |
Output
[1, 2, 3]
Even list using List Comprehension
In this example, we are printing the even numbers from 0 to 10 using List Comprehension.
Python
list = [i for i in range ( 11 ) if i % 2 = = 0 ] print ( list ) |
Output
[0, 2, 4, 6, 8, 10]
Matrix using List Comprehension
In this example, we are assigning integers 0 to 2 to 3 rows of the matrix and printing it using List Comprehension.
Python
matrix = [[j for j in range ( 3 )] for i in range ( 3 )] print (matrix) |
Output
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
Python – List Comprehension
A Python list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list.
Example:
Python
numbers = [ 12 , 13 , 14 ,] doubled = [x * 2 for x in numbers] print (doubled) |
Output
[24, 26, 28]