Apparently list(a) doesn't overallocate, [x for x in a] overallocates at some points, and [*a] overallocates all the time?
Here are sizes n from 0 to 12 and the resulting sizes in bytes for the three methods:
0 56 56 56
1 64 88 88
2 72 88 96
3 80 88 104
4 88 88 112
5 96 120 120
6 104 120 128
7 112 120 136
8 120 120 152
9 128 184 184
10 136 …Run Code Online (Sandbox Code Playgroud) 我惊讶地发现以下内容,在Python 3中,前两个没有提出任何结果:
>>> [] = ()
>>> () = ()
>>> {} = ()
File "<stdin>", line 1
SyntaxError: can't assign to literal
Run Code Online (Sandbox Code Playgroud)
在Python 2.7中,只有第一个没有提出任何东西:
>>> [] = ()
>>> () = ()
File "<stdin>", line 1
SyntaxError: can't assign to ()
>>> {} = ()
File "<stdin>", line 1
SyntaxError: can't assign to literal
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?那么为什么没有提出任何错误呢?为什么() = ()可能在Python 3中被添加为有效?
*注意,您可以用任何空的可迭代(例如[] = set())替换右侧,我只选择一个空的元组用于插图