proper use of list comprehensions - python

2019-01-18 11:57发布

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 > 2]
[3, 4, 5]

Should we use them to perform other procedures? Eg:

>>> a = [1, 2, 3, 4, 5]
>>> b = []
>>> [b.append(i) for i in a]
[None, None, None, None, None]
>>> print b
[1, 2, 3, 4, 5]

or should I avoid the above and use the following instead?:

for i in a:
    b.append(i)

5条回答
相关推荐>>
2楼-- · 2019-01-18 12:23

In the example you give it would make the most sense to do:

b = [i for i in a]

if for some reason you wanted to create b. In general, there is some common sense that must be employed. If using a comprehension makes your code unreadable, don't use it. Otherwise go for it.

查看更多
不美不萌又怎样
3楼-- · 2019-01-18 12:26

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.

查看更多
疯言疯语
4楼-- · 2019-01-18 12:39
b = []
a = [1, 2, 3, 4, 5]
b.extend (a)
查看更多
在下西门庆
5楼-- · 2019-01-18 12:42

Only use list comprehensions if you plan to use the created list. Otherwise you create it just for the GC to throw it again without ever being used.

So instead of [b.append(i) for i in a] you should use a proper for loop:

for i in a:
    b.append(i)

Another solution would be through a generator expression:

b += (i for i in a)

However, if you want to append the whole list, you can simply do

b += a

And if you just need to apply a function to the elements before adding them to the list, you can always use map:

b += map(somefunc, a)
查看更多
放我归山
6楼-- · 2019-01-18 12:45
登录 后发表回答