Creating a list/tuple/dictionary
Duncan Booth
duncan at NOSPAMrcp.co.uk
Tue Jan 7 09:47:23 EST 2003
"Andrew Wilkinson" <ajw126NO at SPAMyork.ac.uk> wrote in
news:3e1ae3b4$0$161$65c69314 at mercury.nildram.net:
> When the Python interpreter comes across a statement such as...
>
> a = [1,2,3]
>
> how does it go about creating that list?
>
> Does it convert the code into something equivalent to
> a = []
> a.append(1)
> a.append(2)
> a.append(3)
> (although obviously it would call the C functions directly)
>
> or is there a quicker method that it uses, if so is that accessible from
> ordinary python code?
The interactive interpreter is your friend:
>>> def f():
a = [1, 2, 3]
>>> import dis
>>> dis.dis(f)
0 SET_LINENO 1
3 SET_LINENO 2
6 LOAD_CONST 1 (1)
9 LOAD_CONST 2 (2)
12 LOAD_CONST 3 (3)
15 BUILD_LIST 3
18 STORE_FAST 0 (a)
21 LOAD_CONST 0 (None)
24 RETURN_VALUE
>>>
>
> The same question applies to tuples and dictionaries, although I'm guess
> that the same answer will apply to all of them.
>
Tuples use BUILD_TUPLE but are otherwise the same. Dictionaries are a bit
messier.
The BUILD_LIST and BUILD_TUPLE bytecodes take a constant number of values
from the stack. If you are building a list of known length then you can use
these codes simply by writing out a list literal, otherwise you have to
build the list up a bit at a time. There isn't any way to get a for loop to
push values onto the stack and then use a BUILD_LIST with a variable to pop
them all in one go.
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list