简体   繁体   中英

Can all for loops in python be converted into list comprehension equivalent?

List comprehension looks more pythonic to me. It is also faster than for loops.

Are ALL for loops in python convertible into list comprehension?

I am using python 3.7

EDIT: It seems like it's a bad idea to use list comprehension when the for loop is long and complicated. It makes the code much less readable.

Yes, sort of.

You can convert nested for loops to list comprehensions, and even use variable assignment with := .

It is true that list comprehensions are slighly faster than for loops, but the difference is so negligible that it is not worth trying to cram a complicated loop into a list comprehension.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM