This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: 关于列表的基础算法问题
Type: behavior Stage: resolved
Components: Windows Versions: Python 3.8
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: paul.moore, steve.dower, terry.reedy, tim.golden, yepan Li, zach.ware
Priority: normal Keywords:

Created on 2020-03-20 02:45 by yepan Li, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
Test01.py yepan Li, 2020-03-20 02:45 错误的算法
Messages (2)
msg364648 - (view) Author: yepan Li (yepan Li) Date: 2020-03-20 02:45
English is very poor so I use Chinese,
这是一个偶然的发现
lis1 = [1,2,3,4,5,6,7,8,9,10]#定义一个列表
lislen = len(lis1)#获得列表长度 此时lislen(列表1)的值为10
lis2 = []*lislen#定义一个新列表长度和第一个列表不一样但是没有元素
print(lis1)#输出测试一下第一个列表正常
for i in lis1:#用i循环遍历数组1
    lis2.insert(lislen,i)#将列表2的第10(lislen)个元素设置为i(i此时为1)
    lislen = lislen-lislen#将lislen(10) = 10(lislen) - 10(lislen) == 0
    #下一次循环应该是lis2.insert(0,i)但是却造成了最终数组倒值的结果
print(lis2)
msg364722 - (view) Author: Terry J. Reedy (terry.reedy) * (Python committer) Date: 2020-03-20 23:36
Test01.py runs as expected with no exceptions.  This issue appears to be based on a misunderstanding of one or both of two things:
a) multiplying an empty list does nothing other than returning a new empty list.
b) list.insert(index, value) treats the index as a slice index.  This is specified in the doc by "same as s[index:index] = [value]". (I spelled out the parameter names.)
https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types

>>> l1, l2 = [], []
>>> l1.insert(6, 0); l2[6:6] = [0]
>>> l1, l2
([0], [0])
History
Date User Action Args
2022-04-11 14:59:28adminsetgithub: 84203
2020-03-20 23:36:20terry.reedysetstatus: open -> closed

type: behavior

nosy: + terry.reedy
messages: + msg364722
resolution: not a bug
stage: resolved
2020-03-20 02:45:45yepan Licreate