Метод List pop() в Python
Сегодня мы рассмотрим метод List pop() в Python. Обычно у нас есть различные встроенные методы для удаления любого элемента из списка в Python. У нас есть del, remove(), а также метод pop() для выполнения этой задачи. Но у каждого из них есть свои отличия. Давайте узнаем, как использовать метод pop() и каковы преимущества использования этого метода.
Работа метода List pop() в Python
По сути, метод pop() в Python выводит последний элемент в списке, если не передан параметр. При передаче с некоторым индексом метод выталкивает элемент, соответствующий индексу.
- Когда передается индекс, метод удаляет элемент по индексу, а также возвращает то же самое.
- Когда ничего не передается, метод удаляет последний элемент и возвращает его там, где функция была ранее вызвана.
Использование списка pop()
Взгляните на пример кода ниже, он иллюстрирует использование встроенного метода pop() в python.
В этом примере ясно, что индекс, предоставленный методу pop(), 10 больше, чем длина списка (4). Следовательно, мы получаем IndexError.
2. Ошибка при пустом списке
Как и в предыдущем разделе, когда мы пытаемся выполнить метод List pop() для пустого списка, мы сталкиваемся с той же самой IndexError. Например:
Итак, мы можем сделать вывод, что при выполнении метода list pop() для пустого списка выдается IndexError.
Следовательно, мы должны проверить, прежде чем применять метод pop(), что список, с которым мы имеем дело, не пуст. Простая проверка длины может решить нашу проблему.
Оператор if-else в Python проверяет, является ли список пустым или нет, и извлекает элемент из списка только тогда, когда len (l1)> 0, т.е. когда список l1 не пуст.
List pop() в стеке Python
Как мы видели в нашем руководстве по Python Stack Tutorial, pop() также является операцией стека, используемой для удаления последней переданной задачи или элемента. Давайте посмотрим, как мы можем реализовать метод list pop() в стеке с помощью списков.
Python .pop() – How to Pop from a List or an Array in Python

Dionysia Lemonaki

In this article, you’ll learn how to use Python’s built-in pop() list method.
By the end, you’ll know how to use pop() to remove an item from a list in Python.
Here is what we will cover:
What are Lists In Python and How to Create Them
Lists are a built-in data type in Python. They act as containers, storing collections of data.
Lists are created by using square brackets, [] , like so:
You can also create a list by using the list() constructor:
As you saw above, a list can contain 0 items, and in that case it is considered an empty list.
Lists can also contain items, or list items. List items are enclosed inside the square brackets and are each separated by a comma, , .
List items can be homogeneous, meaning they are of the same type.
For example, you can have a list of only numbers, or a list of only text:
List items can also be heterogeneous, meaning they can all be of different data types.
This is what sets lists apart from arrays. Arrays require that items are only of the same data type, whereas lists do not.
Lists are mutable, meaning they are changeable. List items can be updated, list items can be deleted, and new items can be added to the list.
How to Delete Elements from a List Using the pop() Method in Python
In the sections that follow you’ll learn how to use the pop() method to remove elements from lists in Python.
The pop() Method — A Syntax Overview
The general syntax of the pop() method looks like this:
Let’s break it down:
- list_name is the name of the list you’re working with.
- The built-in pop() Python method takes only one optional parameter.
- The optional parameter is the index of the item you want to remove.
How to Use the pop() Method With No Parameter
By default, if there is no index specified, the pop() method will remove the last item that is contained in the list.
This means that when the pop() method doesn’t have any arguments, it will remove the last list item.
So, the syntax for that would look something like this:
Let’s look at an example:
Besides just removing the item, pop() also returns it.
This is helpful if you want to save and store that item in a variable for later use.
How to Use the pop() Method With Optional Parameter
To remove a specific list item, you need to specify that item’s index number. Specifically, you pass that index, which represents the item’s position, as a parameter to the pop() method.
Indexing in Python, and all programming languages in general, is zero-based. Counting starts at 0 and not 1 .
This means that the first item in a list has an index of 0 . The second item has an index of 1 , and so on.
So, to remove the first item in a list, you specify an index of 0 as the parameter to the pop() method.
And remember, pop() returns the item that has been removed. This enables you to store it in a variable, like you saw in the previous section.
Let’s look at another example:
In the example above, there was a specific value in the list that you wanted to remove. In order to successfully remove a specific value, you need to know it’s position.
An Overview of Common Errors That Occur When Using the pop() Method
Keep in mind that you’ll get an error if you try to remove an item that is equal to or greater than the length of the list — specifically it will be an IndexError .
Let’s look at the following example that shows how to find the length of a list:
To find the length of the list you use the len() function, which returns the total number of items contained in the list.
If I try to remove an item at position 3, which is equal to the length of the list, I get an error saying that the index passed is out of range:
The same exception would be raised if I had tried to remove an item at position 4 or even higher.
On a similar note, an exception would also be raised if you used the pop() method on an empty list:
Conclusion
And there you have it! You now know how to remove a list item in Python using the pop() method.
I hope you found this article useful.
To learn more about the Python programming language, check out freeCodeCamp’s Scientific Computing with Python Certification.
You’ll start from the basics and learn in an interacitve and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce what you’ve learned.
Полезные методы для работы со списками#
Список — это изменяемый тип данных, поэтому очень важно обращать внимание на то, что большинство методов для работы со списками меняют список на месте, при этом ничего не возвращая.
append #
Метод append добавляет в конец списка указанный элемент:
Метод append меняет список на месте и ничего не возвращает. Если в скрипте надо добавить элемент в список, а потом вывести список print, надо делать это на разных строках кода.
extend #
Если нужно объединить два списка, то можно использовать два способа: метод extend и операцию сложения.
У этих способов есть важное отличие — extend меняет список, к которому применен метод, а суммирование возвращает новый список, который состоит из двух.
Обратите внимание на то, что при суммировании списков в ipython появилась строка Out. Это означает, что результат суммирования можно присвоить в переменную:
Метод pop удаляет элемент, который соответствует указанному номеру. Но, что важно, при этом метод возвращает этот элемент:
Без указания номера удаляется последний элемент списка.
remove #
Метод remove удаляет указанный элемент.
remove() не возвращает удаленный элемент:
В методе remove надо указывать сам элемент, который надо удалить, а не его номер в списке. Если указать номер элемента, возникнет ошибка:
index #
Метод index используется для того, чтобы проверить, под каким номером в списке хранится элемент:
pop() in Python
By
Anandkumar Murugesan

Introduction to pop() in Python
pop() is a method of the complex datatype called list. The list is among the most commonly used complex datatype in python, and the pop() method is responsible for popping an item from the python list. The pop method will remove an item from a given index of the list and returns the removed item. So, in the end, the pop() method will be like a list without the element that was popped.
Syntax:
Web development, programming languages, Software testing & others
The index placed in the method is used to represent the specific element that needs to be popped out of the list. When some element is placed in the list’s argument in the case where that specific element is removed, considering a case where no specific index is specified, it pops the last element in the list. So the understanding is that the index value which is appended when no argument is passed on will be -1, which represents the last element in the list.
How does pop() Function work?
- The pop() will be accepting only one argument for its execution. This argument will be representing the index of the element, which is expected to be popped out from the specified list.
- The process of passing an argument to the list is very much optional; when no argument has been passed, then it represents the value of ‘-1’ as the default. Here basically, the default value of -1 represents the last position in the list.
- The outcome of the pop() method is the item placed at that specific position and along with the item being removed from that specific list.
- When the index value which has been passed is out of the range of the list index, then the ” IndexError: pop index out of rangeexception” will be thrown by the pop() method. So this means the pop() method will not work when the index is out of the index range.
- The key process performed in the backend during this index removal process is as listed, updating the index of the list, removing an element from the index, updating the remaining elements in the index, and removing elements from the index at the reverse of the list.
Examples of pop() in Python
Given below are the examples:
Example #1
Code:
Output:

Explanation:
- A couple of country names are declared as items of a list.
- The third item, namely the county china, is expected to be removed from the list from this list of items.
- This item is achieved by the use of the pop() function by holding the index value of 3 in it.
- The returned value and the updated values are printed in the console.
Example #2
Code:
Output:

Explanation:
- Here it is an integer list that holds a list of all integer values in it.
- The list has initially been printed in the console to display the original list, which is without any pop operation being performed.
- Then third and fourth items from the list are popped out, and the resulting list is again displayed in the console after the pop operation is performed.
Example #3
Code:
Output:

Explanation:
- This example is again very similar to the above-given example; the only difference is here the list is a combination of both the integer and string values.
- The list has initially been printed in the console to display the original list, which is without any pop operation being performed.
- Then third and fourth items from the list are popped out, and the resulting list is again displayed in the console after the pop operation is performed.
Example #4
Code:
Output:

Explanation:
- The above example depicts the exception of ‘pop index out of range error”, the idea is like we have used a list that holds only around 4 valid index values in it, so with holding four values in it, the pop method is called for the 7th index value.
- Since the seventh values are not in the given range of the indexes, the “index out of range” exception has been triggered and printed in the console.
- This is actually a cooked up exception creation kind of an example.
Example #5
Code:
Output:

Explanation:
- The given example shows the use of the pop element in the python list without specifying the index value in the method arguments, so this means none of the index are mentioned so the pop automatically assigns a value of -1, which represents the last element in the list.
- So from out given list [‘India’, ‘Australia’, ‘China’,’Greece’,’Italy’], the final element is Italy.
- So Italy’s value will be removed from the given list and returned as the pop() items value.
- So the returned item along with the manipulated list is printed in the console.
Conclusion
Already python offers a classified list of collection data types, and the efficiency of each of the data types are widely incremented by means of functions like these. They offer greater and superior flexibility in the programming means.
Recommended Articles
We hope that this EDUCBA information on “pop() in Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information.