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

Fine tuning a Hugging Face transformer model for multi-track music generation

To train a PyTorch Transformer for multi-track music generation, the standard paradigm is to convert…

2 weeks ago

what are Transformer, LLM , and GPT

In the field of AI and Natural Language Processing (NLP), The Transformer is the engine…

3 weeks ago

Main framework for PyTorch music generation model

If your goal is purely symbolic melody generation (e.g., generating MIDI files or notes rather…

3 weeks ago

affine_grid() in pytorch

According to PyTorch document, In PyTorch, torch.nn.functional.affine_grid generates a 2D or 3D flow field (sampling…

2 months ago

How to create an Android mobile app with a deep learning AI model ?

Creating an Android mobile app with a deep learning AI model involves several key steps:…

12 months ago

Download source files for R Machine learning

Click here to go to source files for R Machine Learning

1 year ago