简体   繁体   中英

difference between [] and list() in python3

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 ?

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.

[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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM