Online Tutorials & Training Materials | STechies.com
Register Login

Difference between del, remove and pop Methods in Python

|| 0

Difference between del, remove and pop Methods in Python
Stechies

Python Remove Function

It is a method which takes an element as an argument and removes it from a defined list. If the element doesn’t exist in the list, python throws valueError exception.

Example: remove()

petlist = ['dog', 'cat', 'mouse', 'rabbit'] 
petlist.remove('mouse')
print ('Updated list of pets:', petlist)

OUTPUT

$python main.py
('Updated list of pets:', ['dog', 'cat', 'rabbit'])

Python Pop List Function

Python pop() function is used to return the removed element from the given list. It takes the index value of an element as an argument. If there is no index value, python will throw index error: pop index out of range exception.

The index value is an option to provide to a pop() method. If no argument is passed, the default index-1 is taken and return the last item from the list.

For Example

#list of Languages

language = ['Hindi', 'English', 'Marathi', 'Bengali', 'urdu']

#Return value from pop()

#When 4 is passed

return_value = language.pop(4)

print('Return Value: ', return_value)

# Updated List

print('Updated List: ', language)

Output

$python main.py
('Return Value: ', 'urdu')
('Updated List: ', ['Hindi', 'English', 'Marathi', 'Bengali'])
  • If we do not provide any index value then:
language = ['urdu', 'English', 'Marathi', 'Bengali', 'hindi']
# Return value from pop()
# When 4 is passed
return_value = language.pop()
print('Return Value: ', return_value)
# Updated List
print('Updated List: ', language)

Output 

$python main.py
('Return Value: ', 'hindi')
('Updated List: ', ['urdu', 'English', 'Marathi', 'Bengali'])

Del Python List Function

We use del() method to delete an item not to return any value. Using del() method we can also delete a range of value from the given list of elements.

For example

numberslist = [1, 2, 3, 4, 5, 6]
# deleting the third item
del numberslist[2]
print ('the out put list :', numberslist )

 Output

('the out put list :', [1, 2, 4, 5, 6])

Deleting items from 2nd to 4th

numberslist = [1, 2, 3, 4, 5, 6]
# deleting the third item/slice
del numberslist[2:4]
print ('the out put list :', numberslist )

Output

('the out put list :', [1, 2, 5, 6])

Deleting all elements

numberslist = [1, 2, 3, 4, 5, 6]
# deleting the third item
del numberslist[:]
print ('the out put list :', numberslist )

 Output: 

('the out put list :', [])

Python Pop List vs Python Remove List vs Python Del List 

  • Remove() function removes the first matching value from the list.
  • Pop() function is used to return the removed element from the list.
  • Del() function is used to delete an element by index from the list in python.