The remove()
and the pop()
operations are used for list manipulation in Python. They extract certain elements which the user specifies in the list data structure.
pop()
operationWe use this function when we want to remove values from a certain index in the list.
To remove a value at a specific index, we provide the position of the element to be removed within the existing list as an argument to the function.
The syntax to remove an element using pop()
is given below.
<listName>.pop(<index>)
It returns the value removed from the list, which can be stored in a variable for later use.
We can see how the pop
operation works in the Python code snippet below.
# initialize the listmy_list = [12, 9, 2, 7, 3]# display list before pop operationprint("List Before Pop: " + str(my_list))# apply the pop operationelement = my_list.pop(3)# display the popped elementprint("Element Poped: " + str(element))# display the list after element is poppedprint("List After Pop: " + str(my_list))
If we don't provide an index value, the function simply returns the last value in the list.
# initialize the listmy_list = [12, 9, 2, 7, 3]# display list before pop operationprint("List Before Pop: " + str(my_list))# apply the pop operationelement = my_list.pop()# display the popped elementprint("Element Poped: " + str(element))# display the list after element is poppedprint("List After Pop: " + str(my_list))
remove()
operationThe remove()
function removes the first occurrence of an element from the list. If there are duplicate values in a list, it removes the first matching value it encounters from the start but not all the values.
The syntax to remove an element using remove()
is given below.
<listName>.remove(<value>)
It takes a value
as an argument and matches the list for similar values. If the value we specified is not in the list, it then raises a ValueError
.
Another difference is that the remove()
operation does not give a return value upon execution.
We can see how the remove()
operation works in the code snippet below.
# initialize the listmy_list = [12, 9, 2, 7, 3]# display list before remove operationprint("List Before remove: " + str(my_list))# apply the remove operationelement = my_list.remove(9)# we should see that it did not return an elementprint("Element removed: " + str(element))# display the list after element is removeprint("List after applying remove opreation: " + str(my_list))
Note: Unlike the
pop()
operation, inremove()
we need to provide a value as an argument or else we will get an error.
Free Resources