pop() is an inbuilt function in Python that removes and returns last value from the list or the given index value.
index (optional) - The value at index is popped out and removed. If the index is not given, then the last element is popped out and removed.
The last value or the given index value from the list
When index is out of range, it returns IndexError
Code #1 :
6 New List after pop : [1, 2, 3, 4, 5] 4 ('cat', 'bat') 3 New List after pop : [1, 2]
Code #2 :
6 [1, 2, 3, 4, 5] 1 [2, 3, 4, 5]
Code #3 : IndexError
Traceback (most recent call last): File "/home/1875538d94d5aecde6edea47b57a2212.py", line 5, in print(list1.pop(8)) IndexError: pop index out of range
Practical Example :
A list fruit contains fruit_name and property saying its fruit. Another list consume has two items juice and eat. With the help of pop() and append() we can do something interesting.
[['Orange', 'Fruit', 'Juice'], ['Orange', 'Fruit', 'Eat'], ['Banana', 'Fruit', 'Juice'], ['Banana', 'Fruit', 'Eat'], ['Mango', 'Fruit', 'Juice'], ['Mango', 'Fruit', 'Eat']]
- List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()...)
- Python | Convert list of string to list of list
- Python | Convert list of tuples to list of list
- Python | Maximum sum of elements of list in a list of lists
- Python | Sort the values of first list using second list
- Python List Comprehension | Segregate 0's and 1's in an array list
- Python | Convert a nested list into a flat list
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Sort list of list by specified index
- Python | Remove all values from a list present in other list
- Python | Sort list according to other list order
- Python | Convert a string representation of list into list
- Python | Ways to sum list of lists and return sum list
- Python | Convert list of string into sorted list of integer
- Python | Convert list of tuples into list
- Python | Find maximum length sub-list in a nested list
- Python | Convert list of tuples to list of strings
- Python | Check if a nested list is a subset of another nested list
- Python | Merging duplicates to list of list
- Python Program to convert List of Integer to List of String
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.