difference between [] and list() in python3

时光总嘲笑我的痴心妄想 提交于 2021-02-10 19:49:18

问题


I thought that [] and list() were two equal ways to create a list. But if you want a list with dictionnary keys,

var = [a_dict.keys()]

doesn't work since type(var) is [dict_keys], correct syntax is :

var = list(a_dict.keys())

I couldn't find an good explanation on this behaviour. Do you have one ?


回答1:


TL;DR:

  • list() is the same as []
  • list(obj) is not the same as [obj]

a_dict.keys() is a dictionary view object, it returns an object which can be iterated to yield the keys of a_dict. So this line:

[a_dict.keys()]

is saying in python "I'm making a list with one element in it" and that one element is the dict keys iterator. It's a list literal in the syntax.

Now this line:

list(a_dict.keys())

is a call to the list builtin function. This function list attempts to iterate the argument and produce a list. It's a function call in the grammar.

The equivalent list literal (actually list comprehension) would be instead:

[key for key in a_dict.keys()]

Finally, note that dictionary objects iterate by keys anyway, list(a_dict.keys()) would usually be written more simply as as list(a_dict) instead.

Hope this helps.




回答2:


[a_dict.keys()]

This one puts a single element in the list. Just as if you were to write [1]. In this case that one element is going to be a list.

list(a_dict.keys())

The constructor accepts a sequence and will add all elements of the sequence to the container.



来源:https://stackoverflow.com/questions/26932338/difference-between-and-list-in-python3

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