Difference between using [] and list() in Python

When you convert a dict object to a list, it only takes the keys.

However, if you surround it with square brackets, it keeps everything the same, it just makes it a list of dicts, with only one item in it.

>>> obj = {1: 2, 3: 4, 5: 6, 7: 8}
>>> list(obj)
[1, 3, 5, 7]
>>> [obj]
[{1: 2, 3: 4, 5: 6, 7: 8}]
>>> 

This is because, when you loop over with a for loop, it only takes the keys as well:

>>> for k in obj:
...     print k
... 
1
3
5
7
>>> 

But if you want to get the keys and the values, use .items():

>>> list(obj.items())
[(1, 2), (3, 4), (5, 6), (7, 8)]
>>> 

Using a for loop:

>>> for k, v in obj.items():
...     print k, v
... 
1 2
3 4
5 6
7 8
>>> 

However, when you type in list.__doc__, it gives you the same as [].__doc__:

>>> print list.__doc__
list() -> new list
list(sequence) -> new list initialized from sequence's items
>>> 
>>> print [].__doc__
list() -> new list
list(sequence) -> new list initialized from sequence's items
>>> 

Kind of misleading 🙂

Leave a Comment