列表元素的增加操作:
增加操作有以下几种方法:
append():在列表的末尾添加一个元素
extend():在列表的末尾至少添加一个元素
insert():在列表的任意位置添加一个元素
切片:在列表的任意位置添加至少一个元素
代码如下:
#打工人:朱乔栋
#革命尚未成功,同志仍需努力
#向列表的末尾添加一个元素
lst=[10,20,30]
print('添加元素之前的列表',lst,id(lst))
lst.append(100)
print('添加元素之后的列表',lst,id(lst)) #根据得到的地址可知,没有产生新的对象,只是在原列表的末尾增加了一个元素
lst1 = ['hello','world']
lst.append(lst1) #将lst作为一个元素添加到列表的末尾
print(lst)
lst.extend(lst1) #向列表的末尾一次性添加多个元素
print(lst)
#在任意位置上添加一个元素
lst.insert(1,90)
print(lst)
lst2=[True,False,'hello']
#在任意位置上添加多个元素
lst[1:]=lst2 #把lst列表的第二个元素到最后一个元素都切掉,再把lst2添加到lst
print(lst)
运行结果:
添加元素之前的列表 [10, 20, 30] 26035664
添加元素之后的列表 [10, 20, 30, 100] 26035664
[10, 20, 30, 100, ['hello', 'world']]
[10, 20, 30, 100, ['hello', 'world'], 'hello', 'world']
[10, 90, 20, 30, 100, ['hello', 'world'], 'hello', 'world']
[10, True, False, 'hello']
Process finished with exit code 0