【Python基础】列表删除元素的几种方式

1. del

用法:使用del方法可以删除列表任意位置的元素,条件是知道其索引

motorcycles = ['honda', 'yamaha', 'suzuki'] 
print(motorcycles) # ['honda', 'yamaha', 'suzuki'] 
del motorcycles[1] 
print(motorcycles) # ['honda', 'suzuki'] 

2. pop()或者pop(n)

pop()用法:使用pop()可以删除列表末尾的元素,并且可以让你使用这个被删除的元素

motorcycles = ['honda', 'yamaha', 'suzuki'] 
print(motorcycles) # ['honda', 'yamaha', 'suzuki']
popped_motorcycle = motorcycles.pop() 
print(motorcycles) # ['honda', 'yamaha'] 
print(popped_motorcycle) # suzuki 

pop(n)用法:删除指定位置的元素,并且能够使用这个被删除的元素,其中n为索引

motorcycles = ['honda', 'yamaha', 'suzuki'] 
first_owned = motorcycles.pop(1) 
print(motorcycles) # ['honda', 'suzuki'] 
print(first_owned) # yamaha

3. remove(value)

remove(value)用法:有时候,你不知道要从列表中删除的值所处的位置,此时可以使用remove(value),它可以删除值为value的第一个元素

motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati', 'suzuki'] 
print(motorcycles) # ['honda', 'yamaha', 'suzuki', 'ducati', 'suzuki'] 
motorcycles.remove('suzuki') 
print(motorcycles) # ['honda', 'yamaha', 'ducati', 'suzuki']

你可能感兴趣的:(Python基础,python)