proper use of list comprehensions - python

后端 未结 5 917
予麋鹿
予麋鹿 2020-12-10 04:32

Normally, list comprehensions are used to derive a new list from an existing list. Eg:

>>> a = [1, 2, 3, 4, 5]
>>> [i for i in a if i >          


        
5条回答
  •  暖寄归人
    2020-12-10 05:28

    You should indeed avoid using list comprehensions (along with dictionary comprehensions, set comprehensions and generator expressions) for side effects. Apart from the fact that they'd accumulate a bogus list and thus waste memory, it's also confusing. I expect a list comprehension to generate a (meaningful) value, and many would agree. Loops, on the other hand, are clearly a sequence of statements. They are expected to kick off side effects and generate no result value - no surprise.

提交回复
热议问题