首页 > 解决方案 > 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]

标签: pythonpython-3.xlist

解决方案


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 into s 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.


推荐阅读