Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using [] and list() in Python

Tags:

python

list

Can somebody explain this code ?

l3 = [ {'from': 55, 'till': 55, 'interest': 15}, ]
l4 = list( {'from': 55, 'till': 55, 'interest': 15}, )

print l3, type(l3)
print l4, type(l4)

OUTPUT:

[{'till': 55, 'from': 55, 'interest': 15}] <type 'list'>
['till', 'from', 'interest'] <type 'list'>
like image 662
WebOrCode Avatar asked May 16 '14 19:05

WebOrCode


1 Answers

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

like image 152
A.J. Uppal Avatar answered Sep 21 '22 11:09

A.J. Uppal