Сегодня мы рассмотрим метод List pop() в Python. Обычно у нас есть различные встроенные методы для удаления любого элемента из списка в Python. У нас есть del, remove(), а также метод pop() для выполнения этой задачи. Но у каждого из них есть свои отличия. Давайте узнаем, как использовать метод pop() и каковы преимущества использования этого метода.
Содержание
- Работа метода List pop() в Python
- Использование списка pop()
- Ошибки при использовании метода List pop()
- 1. IndexError
- 2. Ошибка при пустом списке
- List pop() в стеке Python
По сути, метод pop() в Python выводит последний элемент в списке, если не передан параметр. При передаче с некоторым индексом метод выталкивает элемент, соответствующий индексу.
Синтаксис:
#pop() method syntax in Python pop(index)
- Когда передается индекс, метод удаляет элемент по индексу, а также возвращает то же самое.
- Когда ничего не передается, метод удаляет последний элемент и возвращает его там, где функция была ранее вызвана.
Использование списка pop()
Взгляните на пример кода ниже, он иллюстрирует использование встроенного метода pop() в python.
list1=[0,1,2,3,4,5,6,7,8,9,10] #pop last element print("pop() returns :",list1.pop(),"; currently list=",list1) #pop element at index 0 print("pop(0) returns :",list1.pop(0),"; currently list=",list1) #pop element at index 1 print("pop(1) returns :",list1.pop(1),"; currently list=",list1) #pop element at index 2 print("pop(2) returns :",list1.pop(2),"; currently list=",list1) #pop element at index 3 print("pop(3) returns :",list1.pop(3),"; currently list=",list1) #pop element at index 4 print("pop(4) returns :",list1.pop(4),"; currently list=",list1)
Вывод:
- Сначала мы инициализируем список list1, как [0,1,2,3,4,5,6,7,8,9,10]. В этом списке мы выполняем соответствующую операцию pop, передавая отдельные индексы.
- pop() – как было сказано ранее, по умолчанию pop() возвращает и удаляет последний элемент из списка. В нашем случае последний элемент был 10, который появляется последовательно.
- pop(0) – выталкивает элемент в list1 в 0-й позиции, которая в нашем случае равна 0.
- Точно так же все операции pop(1), pop(2), pop(3) и pop(4) возвращают элементы по их соответствующим индексам. Это 2, 4, 6 и 8, поскольку мы продолжаем выталкивать элементы из списка.
Ошибки при использовании метода List pop()
1. IndexError
При использовании метода List pop() мы сталкиваемся с ошибкой IndexError, если индекс, переданный методу, превышает длину списка.
Эта ошибка возникает в основном, когда индекс предоставил ее вне диапазона списка. Давайте посмотрим на небольшой пример этого:
list1=["John","Charles","Alan","David"] #when index passed is greater than list length print(list1.pop(10))
Вывод:
Traceback (most recent call last): File "C:/Users/sneha/Desktop/test.py", line 4, in <module> print(list1.pop(10)) IndexError: pop index out of range Process finished with exit code 1
В этом примере ясно, что индекс, предоставленный методу pop(), 10 больше, чем длина списка (4). Следовательно, мы получаем IndexError.
2. Ошибка при пустом списке
Как и в предыдущем разделе, когда мы пытаемся выполнить метод List pop() для пустого списка, мы сталкиваемся с той же самой IndexError. Например:
l1=[] #for empty lists print(l1.pop())
Вывод:
Traceback (most recent call last): File "C:/Users/sneha/Desktop/test.py", line 4, in <module> print(list1.pop()) IndexError: pop from empty list Process finished with exit code 1
Итак, мы можем сделать вывод, что при выполнении метода list pop() для пустого списка выдается IndexError.
Следовательно, мы должны проверить, прежде чем применять метод pop(), что список, с которым мы имеем дело, не пуст. Простая проверка длины может решить нашу проблему.
l1=[] #for empty lists check length before poping elements! if len(l1)>0: print(l1.pop()) else: print("Empty list! cannot pop()")
Вывод:
Empty list! cannot pop()
Оператор if-else в Python проверяет, является ли список пустым или нет, и извлекает элемент из списка только тогда, когда len (l1)> 0, т.е. когда список l1 не пуст.
List pop() в стеке Python
Как мы видели в нашем руководстве по Python Stack Tutorial, pop() также является операцией стека, используемой для удаления последней переданной задачи или элемента. Давайте посмотрим, как мы можем реализовать метод list pop() в стеке с помощью списков.
stack=[] #declare a stack print("Pushing tasks into stack...") for i in range(5): stack.append(i) print("stack=",stack) print("Poping tasks from stack:") #performing repetitive pop() on stack while len(stack)>0: print("pop()=",stack.pop(),"; Currently in Stack:",stack)
Вывод:
- После объявления списка стека мы нажимаем 5 элементов, непрерывно отправляя задачи (элементы) с помощью метода append().
- Как только наша инициализация стека завершена, мы повторяем элементы pop(), пока стек не станет пустым.
- Обратите внимание, что при извлечении элементов из стека мы использовали условие len (stack)> 0 с помощью цикла while. Это гарантирует, что операция pop выполняется только тогда, когда стек не пуст.
If you have been working with lists in Python, you may have encountered the IndexError: pop from empty list
error. This error occurs when you try to remove an item from an empty list using the pop()
method.
In this tutorial, we will explore the reasons why this error occurs and provide you with some solutions to fix it.
Understanding the Error
Before we dive into the solution, let’s first understand why this error occurs. The pop()
method is a built-in list method that is used to remove and return an item from a list. For example, let’s take the list [1, 2, 3]
and call the pop()
method.
# create a list ls = [1, 2, 3] # pop an element from the list val = ls.pop() print(val) print(ls)
Output:
3 [1, 2]
You can see that the pop()
method removed the last value from the list and returned it. Notice that the list is also modified in-place.
When you call pop()
on an empty list, there are no items to remove, and Python raises an IndexError
to indicate that the list is empty.
# empty list ls = [] # pop an element val = ls.pop()
Output:
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[2], line 4 2 ls = [] 3 # pop an element ----> 4 val = ls.pop() IndexError: pop from empty list
We get the IndexError: pop from empty list
error. This is because we are trying to remove an element from an empty list.
Fixing the Error
To fix the “IndexError: pop from empty list” error, you need to check if the list is empty before calling the pop()
method. There are several ways to do this:
1. Using an if statement
ls = [] if ls: ls.pop() else: print("List is empty")
Output:
List is empty
In the above example, we check if ls
is not empty using the if
statement. If the list is not empty, we call the pop()
method to remove the last item. If the list is empty, we print a message indicating that the list is empty.
2. Using a ternary operator
You can alternatively use a ternary operator as well.
ls = [] # pop if list is not empty ls.pop() if ls else print("List is empty")
Output:
List is empty
In the above example, we use a ternary operator to check if ls
is not empty. If the list is not empty, we call the pop()
method to remove the last item. If the list is empty, we print a message indicating that the list is empty.
3. Using a try-except block
ls = [] try: ls.pop() except IndexError: print("List is empty")
Output:
List is empty
In this example, we use a try-except
block to catch the IndexError
that is raised when we try to pop()
an item from an empty list. If the list is empty, the except
block is executed, and we print a message indicating that the list is empty.
Conclusion
In this tutorial, we discussed how to fix the “IndexError: pop from empty list” error in Python. We learned that this error occurs when you try to remove an item from an empty list using the pop()
method. To fix this error, you need to check if the list is empty before calling the pop()
method. We demonstrated three ways to do this: using an if
statement, a try-except
block, and a ternary operator.
You might also be interested in –
- Understand and Fix IndexError in Python
- How to Fix – IndexError list assignment index out of range
- How to Fix – IndexError: single positional indexer is out-of-bounds
- How to Fix – IndexError: too many indices for array in Python
-
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.
View all posts
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.
View all posts