You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中创建长度为4的空列表?为何[]*size方式失效?

Why can't we use [] * size to create a list of specified length, but [None] * size works?

Awesome question—this is a common point of confusion when learning list operations in Python. Let's break down exactly what's happening here.

How list multiplication works in Python

First, let's recall what the * operator does with lists. When you multiply a list by an integer n, Python creates a new list by repeating the elements inside the original list n times. It's not copying the list container itself over and over—it's copying the elements inside it.

Why [] * size fails to create a longer list

[] is an empty list, meaning there are no elements inside it to repeat. So when you do [] * size, you're essentially saying "repeat nothing, size times." Unsurprisingly, the result is still an empty list. Let's test it out:

size = 4
a = [] * size
print(a)  # Output: []
print(len(a))  # Output: 0

No elements to duplicate means your list stays empty, which is why this approach doesn't work for getting a list of your desired length.

Why [None] * size works as expected

[None] is a list that contains one element: None, Python's placeholder for "no value here." When you multiply this list by size, Python takes that single None element and repeats it size times. The end result is a list with exactly size elements (all None), which is exactly what you want. Here's an example:

size = 4
a = [None] * size
print(a)  # Output: [None, None, None, None]
print(len(a))  # Output: 4

Since there's an element to repeat (even if it's just a placeholder like None), you end up with a list of the length you specified.

A quick heads-up to keep in mind

One thing to be careful with: if you use a mutable object (like another list) instead of None—for example, [[]] * 4—all those inner lists are actually the same list under the hood. Changing one will change all of them. But since None is immutable, this isn't a problem when you use [None] * size.

内容的提问来源于stack exchange,提问作者Jin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 00:42:44