1

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 ?

asked Nov 14, 2014 at 14:33
3
  • possible duplicate of In Python, why is list(None) an error but [None] is not? Commented 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. Commented 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! Commented Nov 14, 2014 at 15:24

2 Answers 2

3

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.

answered Nov 14, 2014 at 14:40
1
[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.

answered Nov 14, 2014 at 14:37
2
  • 1
    And note that this has nothing to do with dict_keys, [anything] always constructs a single-element list and list(iterable) always makes a list by iterating over iterable. Commented Nov 14, 2014 at 14:39
  • 1
    Also note that all the other containers work similarly. Commented Nov 14, 2014 at 14:44

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.