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 source files for R Machine learning

Click here to go to source files for R Machine Learning

2 days ago

Python Machine Learning Source Files

Click here to download Python Machine Learning Source Files !

4 weeks ago

Install PyTorch on Windows

PyTorch is a deep learning package for machine learning, or deep learning in particular for…

1 month ago

Topic Modeling using Latent Dirichlet Allocation with Python

Topic modeling is a subcategory of unsupervised machine learning method, and a clustering task in…

2 months ago

Document sentiment classification using bag-of-words in Python

For online Python training registration, click here ! Sentiment classification is a type of machine…

2 months ago

Download R Course source files

Click here to download R Course source files !

11 months ago