python空列表列表初始化_Python列表列表初始化

本文探讨了Python中`[[] for i in range(10)]`为何会创建10个相同的空列表,而非10个独立的空列表。作者揭示了列表生成式中`[]`作为初始值的含义,并指出与`[thing for i in range(10)]`的区别,强调了变量作用域和每次迭代的独立性。
摘要由CSDN通过智能技术生成

I know that

[[]] * 10

will give 10 references of the same empty, And

[[] for i in range(10)]

will give 10 empty lists. But in this example:

def get_list(thing):

return [thing for i in range(10)]

a = get_list([])

a[0].append(1)

print(a)

Why the result is again

[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]

EDIT:

Unlike question List of lists changes reflected across sublists unexpectedly , I understand that Python doesn't do copy in [x]*10.

But why [] is special in [[] for i in range(10)] ? I think this is inconsistent. Instead of creating a empty list [] then pass to [ ___ for i in range(10)], Python take "[]" literally and execute "[]" for every i.

解决方案

That is because thing is the same list.

In [[] for i in range(10)] a new list is generated every time.

In [thing for i in range(10)] it's always the list named thing.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值