pop():移除序列中的一個元素(默認最后一個元素),並且返回該元素的值。
一)移除list的元素,若元素序號超出list,報錯:pop index out of range(超出范圍的流行指數);
A、默認移除最后一個元素
list_1 = [1, 2, 3, 4, 5]
a = list_1.pop()
print (list_1, a)
-->[1, 2, 3, 4] 5
B、移除list中的某一個元素:pop(元素序號)
list_1 = [1, 2, 3, 4, 5]
a = list_1.pop(2)
print (list_1, a)
-->[1, 2, 4, 5] 3
二)移除dict中的元素(只能移除1個元素):pop(),()內不能為空,要有key;若key不在dict內,需要主動給出需要返回的數據,否則報錯;
A、key在dict_1內
dict_1 = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'}
a = dict_1.pop(2)
print(dict_1, a)
-->{1:'a', 3:'c', 4:'d', 5:'e'} b
B、key不在dict_1內:返回pop給定的數據
dict_1 = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'}
a = dict_1.pop(6, [1, 2, 3, 4])
print(dict_1, a)
-->{1:'a', 2:'b', 3:'c', 4:'d', 5:'e'} [1, 2, 3, 4]