简体   繁体   中英

creating list with * operator in python

Why does [0] * 5 create a list [0, 0, 0, 0, 0] , rather than [[0], [0], [0], [0], [0]] ?

Doesn't the * operator duplicate [0] 5 times resulting in [[0], [0], [0], [0], [0]] ?

Just like math:

[0] * 5 = [0] + [0] + [0] + [0] + [0] , which is [0, 0, 0, 0, 0] .

I think people would be more surprised if [0] + [0] suddenly became [[0], [0]] .

For strings, tuples, and lists, + is an append operator. This multiplication holds true for all of them.

阅读序列类型的 Python 文档似乎是因为[0] * 5[0] + [0] + [0] + [0] + [0]的简写(就像乘法在数学中是加法;当“乘”列表时,它的工作原理相同)。

不,它将元素相乘并且 [0] 列表(就像数学集一样)有一个元素 0,而不是 [[0]]。

Use statement below to create [[0], [0], [0], [0], [0]]:

[[0]*1]*5

Note that the list you've mentioned above is a 2d list, so you must use * operator in right way. It means your list has 5 rows and 1 column.

Below is the real result: enter image description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM