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.
list.pop(index)
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. |
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)
even_numbers
..pop(index)
to remove the zero index of the list, which is the number 2, by using even_numbers.pop(0)
.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)
countries
..pop(index)
method to pop out the value of the item in the 2nd index of the list using countries.pop(2)
and assigning the output to a new variable we named new_country
.new_country
.When the index parameter is not passed, the last item of the list is removed.
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.