当前位置: 首页 > 面试题库 >

Why is python list comprehension sometimes frowned upon?

房唯
2023-03-14
问题内容

Many developers I have met suggest it’s best practice to go with simple loops
and if conditions instead of one line list comprehension statements.

I have always found them very powerful as I can fit a lot of code in a single
line and it saves a lot of variables from being created. Why is it still
considered a bad practice?

(Is it slow?)


问题答案:

List comprehensions are used for creating lists, for example:

squares = [item ** 2 for item in some_list]

For loops are better for doing something with the elements of a list (or
other objects):

for item in some_list:
    print(item)

Using a comprehension for its side effects, or a for-loop for creating a list,
is generally frowned upon.

Some of the other answers here advocate turning a comprehension into a loop
once it becomes too long. I don’t think that’s good style: the append calls
required for creating a list are still ugly. Instead, refactor into a
function:

def polynomial(x):
    return x ** 4 + 7 * x ** 3 - 2 * x ** 2 + 3 * x - 4
result = [polynomial(x) for x in some_list]

Only if you’re concerned about speed – and you’ve done your profiling! – you
should keep the long, unreadable list comprehension.



 类似资料:

相关阅读

相关文章

相关问答