What are different examples of the list pop() method in Python?
The list.pop() method is one of the many list methods in Python.
In Python, the list.pop() method is simply used to remove or return an item from a list, or to pop out the item value using its index position in the given list.
Syntax
list.pop(index)
Parameter value
| Parameter | Description |
|---|---|
| index(optional) | When the index is given, the item of the given index is removed from the list. When the index is not given, then the last item of the list is removed. |
Example 1
Let’s remove an element of a list of even numbers up to ten.
even_numbers = [2, 4, 6, 8, 10]# now lets pop out or remove the zero index of the listeven_numbers.pop(0)print(even_numbers)
Explanation
- Line 1: We defined a list of even numbers up to ten and we named it
even_numbers. - Line 4: We used the
.pop(index)to remove the zero index of the list, which is the number 2, by usingeven_numbers.pop(0). - Line 5: We returned the output of the new list.
Example 2
Now, let’s pop out the value of an item from a list of countries, using the index of the item.
countries = ['Almenia', 'Jamaica', 'United kingdom', 'Congo']# now lets pop out the country in the 2nd index of the listnew_country = countries.pop(2)print(new_country)
Explanation
- Line 1: We created a list of countries and we named it
countries. - Line 4: We used the
.pop(index)method to pop out the value of the item in the 2nd index of the list usingcountries.pop(2)and assigning the output to a new variable we namednew_country. - Line 5: We returned the output of the new variable
new_country.
When the index parameter is not passed, the last item of the list is removed.
Code
countries = ['Almenia', 'Jamaica', 'United kingdom', 'Congo']# now lets use the list.pop() method without an index valuecountries.pop()print(countries)
We can see from the code above that the last item in the list was removed using the list.pop() method without the index.