insert在python里是什么意思

insert在python里是什么意思,第1张

insert()是Python中的内置函数,可将给定元素插入列表中的给定索引。

python的insert函数中有两个必填参数,第一个是填充的位置,第二个是填充的内容。必须有小数点,不然报错。一般用1.0,就是往下面一行行的写。

insert()的参数和返回值

参数:index - the index at which the element has to be inserted.

element - the element to be inserted in the list.

返回值:This method does not return any value but

it inserts the given element at the given index.

在 python 中,列表变量调用 += 本质上是在执行列表变量的 extend 方法,不会修改变量的引用

def demo(num, num_list):

print("函数内部代码")

# num = num + num

num += num

# num_list.extend(num_list) 由于是调用方法,所以不会修改变量的引用

# 函数执行结束后,外部数据同样会发生变化

num_list += num_list

print(num)

print(num_list)

print("函数代码完成")

gl_num = 9

gl_list = [1, 2, 3]

demo(gl_num, gl_list)

print(gl_num)

print(gl_list)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

运行结果

9

[1, 2, 3, 1, 2, 3]

1

2

1

2

可以看出 += 其实是对列表extend方法的调用,如果我们不想改变原有的列表属性,将num_list += num_list代码改变为num_list = num_list + num_list,这样就不改变原有的属性


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11716774.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存