Python pop list elements

Метод List pop() в Python

Сегодня мы рассмотрим метод List pop() в Python. Обычно у нас есть различные встроенные методы для удаления любого элемента из списка в Python. У нас есть del, remove(), а также метод pop() для выполнения этой задачи. Но у каждого из них есть свои отличия. Давайте узнаем, как использовать метод pop() и каковы преимущества использования этого метода.

Работа метода 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, передавая отдельные индексы.
  • pop() – как было сказано ранее, по умолчанию pop() возвращает и удаляет последний элемент из списка. В нашем случае последний элемент был 10, который появляется последовательно.
  • pop(0) – выталкивает элемент в list1 в 0-й позиции, которая в нашем случае равна 0.
  • Точно так же все операции pop(1), pop(2), pop(3) и pop(4) возвращают элементы по их соответствующим индексам. Это 2, 4, 6 и 8, поскольку мы продолжаем выталкивать элементы из списка.
Traceback (most recent call last): File "C:/Users/sneha/Desktop/test.py", line 4, in print(list1.pop(10)) IndexError: pop index out of range Process finished with exit code 1

В этом примере ясно, что индекс, предоставленный методу pop(), 10 больше, чем длина списка (4). Следовательно, мы получаем IndexError.

Читайте также:  Success php on line 53

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 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()")

Оператор 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)

Pop в стеке

  • После объявления списка стека мы нажимаем 5 элементов, непрерывно отправляя задачи (элементы) с помощью метода append().
  • Как только наша инициализация стека завершена, мы повторяем элементы pop(), пока стек не станет пустым.
  • Обратите внимание, что при извлечении элементов из стека мы использовали условие len (stack)> 0 с помощью цикла while. Это гарантирует, что операция pop выполняется только тогда, когда стек не пуст.

Источник

Python .pop() – How to Pop from a List or an Array in Python

Dionysia Lemonaki

Dionysia Lemonaki

Python .pop() – How to Pop from a List or an Array in Python

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:

#an empty list my_list = [] print(my_list) print(type(my_list)) #output #[] #

You can also create a list by using the list() constructor:

#an empty list my_list = list() print(my_list) print(type(my_list)) #output #[] #

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:

# a list of integers my_numbers_list = [10,20,30,40,50] # a list of strings names = ["Josie", "Jordan","Joe"] print(my_numbers_list) print(names) #output #[10, 20, 30, 40, 50] #['Josie', 'Jordan', 'Joe'] 

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.

#a list containing strings, integers and floating point numbers my_information = ["John", "Doe", 34, "London", 1.76] print(my_information) #output #['John', 'Doe', 34, 'London', 1.76] 

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:

  • 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:

#list of programming languages programming_languages = ["Python", "Java", "JavaScript"] #print initial list print(programming_languages) #remove last item, which is "JavaScript" programming_languages.pop() #print list again print(programming_languages) #output #['Python', 'Java', 'JavaScript'] #['Python', 'Java'] 

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.

#list of programming languages programming_languages = ["Python", "Java", "JavaScript"] #print initial list print(programming_languages) #remove last item, which is "JavaScript", and store it in a variable front_end_language = programming_languages.pop() #print list again print(programming_languages) #print the item that was removed print(front_end_language) #output #['Python', 'Java', 'JavaScript'] #['Python', 'Java'] #JavaScript 

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.

#list of programming languages programming_languages = ["Python", "Java", "JavaScript"] #remove first item and store in a variable programming_language = programming_languages.pop(0) #print updated list print(programming_languages) #print the value that was removed from original list print(programming_language) #output #['Java', 'JavaScript'] #Python 

Let’s look at another example:

#list of programming languages programming_languages = ["Python", "Java", "JavaScript"] #remove "Java" from the list #Java is the second item in the list which means it has an index of 1 programming_languages.pop(1) #print list print(programming_languages) #output #['Python', 'JavaScript'] 

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:

#list of programming languages programming_languages = ["Python", "Java", "JavaScript"] #find the length of the list print(len(programming_languages)) #output #3 

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:

#list of programming languages programming_languages = ["Python", "Java", "JavaScript"] programming_languages.pop(3) #output # line 4, in # programming_languages.pop(3) #IndexError: pop index 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:

#empty list programming_languages = [] #try to use pop() on empty list programming_languages.pop() #print updated list print(programming_languages) #output #line 5, in # programming_languages.pop() #IndexError: pop from 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.

Thanks for reading and happy coding!

Источник

Python List pop() Method

The pop() method removes the element at the specified position.

Syntax

Parameter Values

Parameter Description
pos Optional. A number specifying the position of the element you want to remove, default value is -1, which returns the last item

More Examples

Example

Return the removed element:

fruits = [‘apple’, ‘banana’, ‘cherry’]

Note: The pop() method returns removed value.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью