python空列表列表初始化,Python列表列表初始化

本文探讨了Python中列表推导式的微妙之处,解释了为什么`[thing for i in range(10)]`在`thing`为空列表时会导致所有子列表共享同一引用。通过实例分析,揭示了Python在处理空列表时的特殊行为,并对比了`[[] for i in range(10)]`与`[[]*10]`的区别,帮助理解Python列表的复制和引用概念。
摘要由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、付费专栏及课程。

余额充值