Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

Creating a list in Python- something sneaky going on?

Apologies if this doesn't make any sense, I'm very new to Python!

From testing in an interpreter, I can see that list() and [] both produce an empty list:

>>> list()
[]
>>> []
[]

From what I've learned so far, the only way to create an object is to call its constructor (__init__), but I don't see this happening when I just type []. So by executing [], is Python then mapping that to a call to list()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Those two constructs are handled quite differently:

>>> import dis
>>> def f(): return []
... 
>>> dis.dis(f)
  1           0 BUILD_LIST               0
              3 RETURN_VALUE        
>>> def f(): return list()
... 
>>> dis.dis(f)
  1           0 LOAD_GLOBAL              0 (list)
              3 CALL_FUNCTION            0
              6 RETURN_VALUE        
>>> 

The [] form constructs a list using the opcode BUILD_LIST, whereas the list() form calls the list object's constructor.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...