Python List pop() Method | Novice Tutorial
Description
The pop() method removes an element from a list (default is the last element) and returns the value of that element.
Syntax
The syntax for the pop() method is:
list.pop()
Parameters
index-- Optional parameter, the index value of the element to be removed, cannot exceed the list length. Defaults toindex=-1, removing the last list value.
Return Value
This method returns the element object removed from the list.
Example
The following example demonstrates how to use the pop() method:
Example 1
#!/usr/bin/python3
list1 = ['Google', '', 'Taobao']
list1.pop()
print ("List now : ", list1)
list1.pop(1)
print ("List now : ", list1)
The output of the above example is:
List now : ['Google', '']
List now : ['Google']
Here is an example of popping an element and returning the popped element:
#!/usr/bin/python3
list1 = ['Google', '', 'Taobao']
pop_obj=list1.pop(1)
print ("Popped element : ", pop_obj)
print ("List now : ", list1)
The output of the above example is:
Popped element :
List now : ['Google', 'Taobao']
Error Example
The following example demonstrates an error when popping an element from an empty list:
#!/usr/bin/python3
list1 = []
pop_obj=list1.pop()
print ("Popped element : ", pop_obj)
print ("List now : ", list1)
The output of the above example is:
Traceback (most recent call last):
File "test.py", line to 4, in
pop_obj=list1.pop()
IndexError: pop from empty list
YouTip