When I assign a list to variable why Pycharm give me a prompt that is “this list creation could be rewritten as a list literal”?

橙三吉。 提交于 2020-05-09 18:32:34

问题


I am a Python beginner and have a puzzle. When I write code like this:

lst = [1, 2, 3, 4]

Pycharm give me a prompt that is "this list creation could be rewritten as a list literal". But if it's replaced by

lst = list([1, 2, 3, 4])

Pycharm doesn't say anything. Who could tell me why?

Is this code like lst = [1, 2, 3, 4] legal in Python? Can I ignore prompt?


回答1:


Check your code to make sure you don't have lst somewhere else as lst=[].

If you type the following:

lst= []
# more code
lst = [1, 2, 3, 4]

You'll receive the prompt you got. You won't run into problems if you keep it that way but it's bad practice.

In those two cases you are using a function to change the variable: list() and append(). In the previous one where you're just redefining the variable explicitly.

Another improper example:

a = 7
# some code that has nothing to do with "a" or uses it
a = 8

Just set a = 8 to begin with. No need to store a = 7.




回答2:


It's totally legal to write code like that in Python. However, writing code like

lst = [1, 2, 3, 4, 12]

would be "better" than

lst = [1, 2, 3, 4]
... # code has nothing do to with lst
lst.append(12)

In general, the former one would have better performance than the latter one, but if the latter one is more readable in your case/you have a good reason doing that, then you can ignore the PyCharm prompt.

If it bothers you, you can turn this inspection off in

"PyCharm->settings->editor->inspection->Python->List creation could be..."



来源:https://stackoverflow.com/questions/31063384/when-i-assign-a-list-to-variable-why-pycharm-give-me-a-prompt-that-is-this-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!