Python

List comprehension in Python

We provide effective and economically affordable online training courses for R and Python, click here for more details and course registration !

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.

For getting more knowledge of Python and a preview of our training course, you can watch Python tutorial videos on our YouTube channel !

wilsonzhang746

Recent Posts

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago