python - In python why is list[i:i] = [n] insert an element in list[i:i]
问题描述
Why do python have this behavior ? how can it be explained ?
mylist=[5, 9, 13, 15, 16]
n=14
i=0
mylist[i:i] = [n]
print(mylist)
Output:
[14, 5, 9, 13, 15, 16]
解决方案
In Python doc,
s[ i : j ] = t --> slice of s from i to j is replaced by the contents of the iterable t
s.append(x) --> appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
s.insert(i, x) --> inserts
x
intos
at the index given by i (same as s[i:i] = [x])
s[i:i] = [x]
behaves like insert
and s[len(s):len(s)] = [x]
behaves like append
.
Let's examine s[i:j] = [t]
,
1. If i == j
, then it will behave like insert
and inserts t
's content to s
in index j
2. If i == j == len(s)
, then it will behave like append
and appends t
's content to s
.
3. If i != j
then slice of s from i
to j
is replaced by the contents of the iterable t
.
Your question is case 1. It will behave like insert and 14 will be inserted position 0.
Case 3 Example
a = [5, 15, 13, 8, 16]
t = [4,2]
a[1:3] = t
print(a) # [5, 4, 2, 8, 16]
What it really happens that slice of 1 to 3 (15 and 13) has replaced by contents of t
.
推荐阅读
- python - “列表”对象没有属性“板”
- alpine.js - Alpine.js 将 select 的变化绑定回 x-data
- node.js - 将用户从 Firebase Auth 复制/迁移到 Google Identity Platform
- reactjs - 主题中useState的访问值
- python - python中的长时间延迟函数调用?
- numpy - numpy 中 : 和 , 之间的区别
- java - Android 应用程序电子邮件收件人选项不起作用
- c# - 如何使用SqlKata(Dapper)从多个列中获取值作为IEnumerable
- python - 多项式的遗传算法优化
- html - jQuery removeClass 函数不起作用