Get the App
SLTechnology News&Howtos  ›  Development  › 

How python uses list comprehension instead of the original for loop

Shulou Source: shulou.com Published: 2022-06-01 05:15:50 10月03日 Update

Editor to share with you how python uses list comprehension instead of the original for cycle. I hope you will get something after reading this article. Let's discuss it together.

Use list comprehension instead of the original for loop

Suppose we want to create a list with a specific value, in this case a list of all squares between 0 and 9. The tedious approach is to create an empty list, then use a for loop to calculate it, and append it to the list:

Squares = [] for i in range (10): squares.append (iTuni)

An easier way is list comprehension. Here we only need one line to do the same thing:

# better: squares = [iTuni for i in range (10)]

List comprehension is very powerful, even including if statements. Note that the use of list comprehension is a little controversial. It should not be overused, especially if it harms the readability of the code. But personally, I think this grammar is clear and concise.

After reading this article, I believe you have a certain understanding of "how python uses list comprehension instead of the original for cycle". If you want to know more about it, welcome to follow the industry information channel, thank you for reading!

Tags: Loops primitive methods articles lengthy powerful concise boring one line personal between things code readability done more knowledge capabilities industries statements Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi vpn MySQL Shulou Technology Microsoft