xxxxxxxxxx
>>> a=[1,2,3]
>>> a.remove(2)
>>> a
[1, 3]
>>> a=[1,2,3]
>>> del a[1]
>>> a
[1, 3]
>>> a= [1,2,3]
>>> a.pop(1)
2
>>> a
[1, 3]
>>>
xxxxxxxxxx
# if you want to remove all 2's from the list
x = [1,2,3,2,2,2,3,4]
new_x = list(filter(lambda a: a != 2, x))
# the output:
# [1, 3, 3, 4]
xxxxxxxxxx
>>> a = ['a', 'b', 'c', 'd']
>>> a.remove('b')
>>> print a
['a', 'c', 'd']
xxxxxxxxxx
l = ['Alice', 'Bob', 'Charlie', 'Bob', 'Dave']
print(l)
# ['Alice', 'Bob', 'Charlie', 'Bob', 'Dave']
l.remove('Alice')
print(l)
# ['Bob', 'Charlie', 'Bob', 'Dave']
xxxxxxxxxx
# create a list
prime_numbers = [2, 3, 5, 7, 9, 11]
# remove 9 from the list using 'remove' method
prime_numbers.remove(9)
# prime_numbers are automatically updated. No seperate initialisation is required
print('Updated List: ', prime_numbers)
# Output: Updated List: [2, 3, 5, 7, 11]
# remove 9 from the list using 'pop' method
# remove 9 from the list and returns the value 9.
# We need to mention the position of the item that needs to be removed instead of the actual value.
prime_numbers.pop(4)
# returns/displays 9
# prime_numbers are automatically updated. No seperate initialisation is required
print('Updated List: ', prime_numbers)
# Output: Updated List: [2, 3, 5, 7, 11]
xxxxxxxxxx
# Python program to remove multiple
# elements from a list
# creating a list
list1 = [11, 5, 17, 18, 23, 50]
# items to be removed
unwanted_num = {11, 5}
list1 = [ele for ele in list1 if ele not in unwanted_num]
# printing modified list
print("New list after removing unwanted numbers: ", list1)
xxxxxxxxxx
# Python program to remove multiple
# elements from a list
# creating a list
list1 = [11, 5, 17, 18, 23, 50]
# given index of elements
# removes 11, 18, 23
unwanted = [0, 3, 4]
for ele in sorted(unwanted, reverse = True):
del list1[ele]
# printing modified list
print (*list1)
xxxxxxxxxx
prime_numbers = [2, 3, 5, 7, 9, 11, 13]
# remove 9 from the list
prime_numbers.remove(3)
# Updated prime_numbers List
print('Updated List: ', prime_numbers)
# Output: Updated List: [2, 3, 5, 7, 9, 11, 13]