What is the difference between implementation of list() and [] in py3.x?

Here is the sample code1 and its result.

d ={
    "name":"looser",
    "roll":6666,
    "profile" : "developer"
}

print("list formatted dict is {}".format([d]))

for k,v in [d.items()]:
    if d[k] is "developer":
        d.pop(k)
    else:
        print(k)

result:

list formatted dict is [{'name': 'looser', 'roll': 6666, 'profile': 'developer'}]
Traceback (most recent call last):
  File "/Users/rough/try.py", line 18, in <module>
    for k,v in [d.items()]:
ValueError: too many values to unpack (expected 2)

Process finished with exit code 1

Here is the sample code2 with modified form.

d ={
    "name":"looser",
    "roll":6666,
    "profile" : "developer"
}

print("list formatted dict is {}".format([d]))

for k,v in list(d.items()):
    if d[k] is "developer":
        d.pop(k)
    else:
        print(k)

result:

list formatted dict is [{'name': 'looser', 'roll': 6666, 'profile': 'developer'}]
name
roll

Process finished with exit code 0

On many places people tell me there is no difference, is it true there is no difference.If there is no difference then why such result.

Because one is solving my problem of **RuntimeError: dictionary changed size during iteration **


there's almost no difference between:

a = list()

and

a = []

except for the time taken for the name lookup vs built-in [] (Why is [] faster than list()?)

but if you pass any item to list , list tries to iterate on it to build a new list.

From help(list) output:

class list(object)

| list() -> new empty list

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

So there are 2 "modes" when creating a list object.

Try list(3) you'll get TypeError: 'int' object is not iterable error, try [3] you'll get a list with 1 element in it.

That's no different when passing your d.items() object.

  • list(d.items()) iterates/converts the items to a list of tuples.
  • [d.items()] creates a list with a single element inside: d.items() (which explains that unpacking to 2 elements fails)
  • Also note that for k,v in list(d.items()): is not necessary unless you want to remove items from your dictionary while iterating on it (which seems to be the problem you're having, seeing your recent edit)

    Apart from that case, no need to turn to a list as d.items() is already iterable and wrapping that in a list does nothing useful (and it's even slower)


    [] is a literal which will create the list exactly as you define it. ['a'] is a list with one item. [d.items()] is also a list with one item. That one item is many items though which fail to unpack into just k, v .

    list() is the constructor form which takes an iterable to create a new list. list('a') equals ['a'] . list('ab') equals ['a', 'b'] ; it iterates over the iterable string 'ab' . list(d.items()) iterates over all items in d.items() and creates the list [('name', 'looser'), (...)] ; that is a list with many two-item tuples, which individually unpack into k, v .

    链接地址: http://www.djcxy.com/p/31702.html

    上一篇: 如何以一种故障安全的方式将内容从一个词典用Python语言映射到另一个词典?

    下一篇: py3.x中list()和[]的实现有什么区别?