当通过调用列表(a)制作列表副本时,Python是否会预先分配列表的确切大小?

发布于 2025-02-11 14:55:38 字数 303 浏览 1 评论 0原文

我的理解是,在将数百个项目附加到列表中时,最终Python将创建一个带有更大缓冲区的全新列表,以便可以继续添加其他元素。

但是,假设我有以下清单:

a = [1, 2, 3, 4, 5]
b = list(a)

既然Python从技术上知道B将拥有多少要素,那么它将采用“智能”方法并提前分配5个空间?

因此,与使用for a循环相比,上述方法在创建深层副本方面会更有效吗?例如:

b = []
for i in a:
    b.append(i)

It is my understanding that when appending hundreds of items to a list, eventually Python will create a brand new list with a larger buffer so that additional elements can continue to be added.

However, let's say I have a list as follows:

a = [1, 2, 3, 4, 5]
b = list(a)

Since Python technically knows how many elements b will hold, will it take the "smart" approach and allocate 5 spaces in advance?

Accordingly, would the above approach be more efficient in creating a deep copy compared to using a for loop? For example:

b = []
for i in a:
    b.append(i)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文