List comprehension is a concise way to create a list in Python. It is usually a composition of an expression with a for loop statement in the bracket. In the following code, we create a list of squared numbers using list comprehension.
#to create a list of squared number from 10 to 20
exp_list = [element**2 for element in range(10,21)]
print(exp_list)
#output
[100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
Here can we see element**2 is the expression. The later part of the statement is a for loop, in which each value for element in the for loop will be passed to the former expression. Note that there is no colon or comma inside the whole list comprehension statement.
If not using list comprehension, the same result can be got using the following code.
elements = list(range(10,21))
exp_list = []
# for loop to calculate the square and attach each element
for element in elements:
exp_list.append(element**2)
print(exp_list)
[100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
We can see by using list comprehension, a lot of lines of code can be spared.
Click here to download Python Course Source Files !
For online Python training registration, click here ! Pandas provides flexible ways of generating data…
For online Python training registration, click here ! Data frame is the tabular data object…
Click her for course registration ! When a data frame in Python is created via…
We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…