惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
SegmentFault 最新的问题
G
Google Developers Blog
H
Help Net Security
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Proofpoint News Feed
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
B
Blog RSS Feed
爱范儿
爱范儿
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 三生石上(FineUI控件)
大猫的无限游戏
大猫的无限游戏
人人都是产品经理
人人都是产品经理
GbyAI
GbyAI
D
Docker
Hugging Face - Blog
Hugging Face - Blog
I
InfoQ
博客园 - 司徒正美
Last Week in AI
Last Week in AI
Microsoft Security Blog
Microsoft Security Blog
美团技术团队
Stack Overflow Blog
Stack Overflow Blog
M
MIT News - Artificial intelligence

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN
The Correct Way to Create List of Empty List in Python
2020-11-22 · via jdhao's digital space

TL;DR: do not use list multiplication to initialize an empty list of list, or you will end up wasting hours debugging your program.

I wrote some Python code for my project and found that the result isn’t correct. So I spent quite some time debugging the whole working process of this program, and found sadly that the culprit is a list of empty list, which is wrongly initialized.

What is the resulting list, if we do the following in Python?

x = [[]] * 3
x[0].append(1.0)

I expect x now becomes [[1.0], [], []]. Instead, it becomes [[1.0], [1.0], [1.0]]. This is because when we use multiplication to create list x, we actually created 3 references to an empty list. List is a mutable object in Python. When we append values to a list, we haven’t changed its identity. As a result, changing either one of the 3 sub-list will change the others, since they all refer to the same list.

Note that things are different when we create a list of same immutable objects using multiplication. For example, if we create a list of same int, and then change one of the them, the other elements will not change, because we can not change the value of immutable types, assigning a new int to a list element will make it point to another address.

In [18]: a = [1] * 2

In [19]: a
Out[19]: [1, 1]

In [20]: print(id(a[0]), id(a[1]))
4438635584 4438635584

In [21]: a[0] = 2

In [22]: print(id(a[0]), id(a[1]))
4438635616 4438635584

To create a list 3 empty lists, we may use list comprehension instead:

x = [[] for _ in range(3)]

In each iteration, a new empty list is created. So the 3 sub-list are independent of each other. Changing one won’t affect the others.

References#