Skip to content Skip to sidebar Skip to footer

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],

Solution 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:

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

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

Post a Comment for "Difference Between [] And List() In Python3"