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 ?
-
possible duplicate of In Python, why is list(None) an error but [None] is not?jonrsharpe– jonrsharpe2014年11月14日 14:37:00 +00:00Commented Nov 14, 2014 at 14:37
-
what i learn from this, always using new_list = list() is safier than new_list = []. afterwards one does not mix both syntax.comte– comte2014年11月14日 15:23:26 +00:00Commented Nov 14, 2014 at 15:23
-
Once you understand the difference between the two forms, it's not a problem. However, if you feel the extra few characters saves you some confusion, go for it!jonrsharpe– jonrsharpe2014年11月14日 15:24:44 +00:00Commented Nov 14, 2014 at 15:24
2 Answers 2
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.
-
1And note that this has nothing to do with
dict_keys
,[anything]
always constructs a single-element list andlist(iterable)
always makes a list by iterating overiterable
.user395760– user3957602014年11月14日 14:39:48 +00:00Commented Nov 14, 2014 at 14:39 -
1Also note that all the other containers work similarly.Karoly Horvath– Karoly Horvath2014年11月14日 14:44:22 +00:00Commented Nov 14, 2014 at 14:44