Online Tutorials & Training Materials | STechies.com
Register Login

Difference between Del, Remove and Pop in Python

|| 0

Difference between Del, Remove and Pop in Python
Stechies

Python Remove Function

Python Remove 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 than valueError exception is thrown.

Example: remove()

petlist = ['kutta', 'billi', 'tota', 'khargosh'] 
petlist.remove('tota')
print ('Updated list of pets:', petlist)

OUTPUT

$python main.py
('Updated list of pets:', ['kutta', 'billi', 'khargosh'])

Python Pop List Function

Python Pop method removes an element according to index position in a given list, with a return of removed element. It takes the index value of an element as an argument. If the index value is not there then index error: pop index out of range exception is thrown.

The index value is the 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 = ['Hini', '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: ', ['Hini', '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

The del() method can delete an item with the help of index but does not return any value. And also we can delete a range from a given a 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 returns the removed element from the list.
  • Del() function is used to delete an element by index from the list in python.


Related Articles