Skip to content Skip to sidebar Skip to footer

Difference Between Using [] And List() In Python

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

Solution 1:

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

>>>printlist.__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 :)

Solution 2:

  • The former just wraps the entire item in square brackets [], making it a one-item list:

    >>> [{'foo': 1, 'bar': 2}][{'foo': 1, 'bar': 2}]
  • The latter iterates over the dictionary (getting keys) and produces a list out of them:

    >>> list({'foo': 1, 'bar': 2})
    ['foo', 'bar']
    

Solution 3:

>>> help(list)

Help onclass list inmodule __builtin__:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items

In the first case the notation indicates you're creating a list with a dictionary as its object. The list is created empty and the dictionary is appended as an object.

In the second case you're calling the second form of the list constructor - "initialized from iterable's items". In a dictionary it's the keys that are iterable, so you get a list of the dictionary keys.

Solution 4:

The list is a constructor that will take any basic sequence (so tuples, dictionaries, other lists, etc.) and can turn them into lists. Alternatively, you could make the lists with [] and it will make a list with all the things you put inside the brackets. You can actually accomplish the same things with list comprehension.

13 = [item for item in {'from': 55, 'till': 55, 'interest': 15}]
 14 = list({'from': 55, 'till': 55, 'interest': 15})

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