末尾添加 append
motorcycles = ['张三', '李四', '王五'];
print(motorcycles) #=> ['张三', '李四', '王五'];
motorcycles.append('赵六') #要先append再打印 不然可能打印出None
print(motorcycles) #=> ['张三', '李四', '王五','赵六'];
中间添加 insert
motorcycles.insert(0,'刘一') #.insert(索引,'插入的值')
print(motorcycles) #=> ['刘一','张三', '李四', '王五','赵六'];
删除del()
#使用del语句删除元素 如果知道删除元素的位置,可使用del语句
motorcycles = ['刘一','张三', '李四', '王五'];
print(motorcycles) #=> ['刘一','张三', '李四', '王五'];
del motorcycles[0]
print(motorcycles) #=> ['张三', '李四', '王五'];
删除pop()
#使用方法pop()删除元素,删除最后一项,并可获取删除的值
pop_motorcycles = motorcycles.pop();//删除的值
print(motorcycles) #=> ['张三', '李四']
print(pop_motorcycles) #=> ['王五']
#使用pop弹出列表中任何位置处的元素
motorcycles = ['张三', '李四', '王五'];
first_owned = motorcycles.pop(0)
print(first_owned) #=> ['张三']
如果你要从列表中删除一个元素,并且不再使用它,就使用del语句;如果你要在删除元素后还能继续使用它,就使用方法pop()
删除remove()
#remove()根据值删除元素
#使用remove()从列表中删除元素时,也可接着使用它的值
motorcycles = ['张三', '李四', '王五'];
# motorcycles.remove('李四')
x = '李四'
remove_motorcycles = '李四'
motorcycles.remove(remove_motorcycles)
print(motorcycles) #=> ['张三', '王五']
print(remove_motorcycles) #=> 李四
#方法remove()只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值