Pop from empty list ошибка

I’m fairly new at coding python… Trying to understand the .pop() function and how to pop an item from a list and append to a new list. Can someone help me with this code to see why it’s telling me that I’m popping from an empty list?

more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] 
new_list = []

while len(new_list) <= 8:
    stuff = more_stuff.pop() 
    print "Adding: ", stuff
    new_list.append(stuff)

print new_list

I’m getting this result when running the code:

Traceback (most recent call last):
  File "testpop.py", line 5, in <module>
    stuff = more_stuff.pop()
IndexError: pop from empty list

linusg's user avatar

linusg

6,2434 gold badges28 silver badges77 bronze badges

asked Jan 22, 2017 at 13:33

Fahad Bubshait's user avatar

1

The indexes in a list starts from zero.

So, in more_stuff[7] you will get ‘Boy’ which is the last one.

Your code is trying to pop another element after ‘Boy’ which does not exist.

All you need to fix is:

while len(new_list) <= 7:

EDIT:

You could do it with list comprehension as well:

more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana",
"Girl", "Boy"] 

new_list = [more_stuff.pop() for __ in xrange(len(more_stuff))]

print new_list

answered Jan 22, 2017 at 13:37

omri_saadon's user avatar

omri_saadonomri_saadon

10.1k7 gold badges33 silver badges58 bronze badges

1

You should check your condition on the more_stuff list, because that will run out of items:

while len(more_stuff) > 0:
    ...

answered Jan 22, 2017 at 13:40

Maurice Meyer's user avatar

Maurice MeyerMaurice Meyer

17.1k4 gold badges30 silver badges47 bronze badges

1

while more_stuff is empty, len(more_stuff)=0 , the pop() will still work .

Use list as condition, if the list is empty, the bool value is False

more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana",
"Girl", "Boy"] 
new_list = []
while more_stuff:
    stuff = more_stuff.pop() 
    print ("Adding: ", stuff)
    new_list.append(stuff)

Any object can be tested for truth value, for use in an if or while
condition or as operand of the Boolean operations below. The following
values are considered false:

  • None
  • False
  • zero of any numeric type, for example, 0, 0.0, 0j.
  • any empty sequence, for example, », (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a bool() or len() method, when that method returns the integer zero or bool value False.

answered Jan 22, 2017 at 13:37

宏杰李's user avatar

宏杰李宏杰李

11.8k2 gold badges28 silver badges35 bronze badges

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

Содержание

  1. Работа метода List pop() в Python
  2. Использование списка pop()
  3. Ошибки при использовании метода List pop()
  4. 1. IndexError
  5. 2. Ошибка при пустом списке
  6. 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)

Вывод:

Метод List 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, поскольку мы продолжаем выталкивать элементы из списка.

Ошибки при использовании метода 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)

Вывод:

Pop в стеке

  • После объявления списка стека мы нажимаем 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.

fix "IndexError: pop from empty list" in python

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 Raj

    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

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:

  1. An overview of lists in Python
  2. How to delete list items using pop()
    1. Syntax of the pop() method
    2. Use the pop() method with no parameter
    3. Use the pop() method with optional parameter
    4. Dealing with common errors

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

#[]
#<class 'list'>

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

#[]
#<class 'list'>

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.pop(index)

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:

list_name.pop()

Let’s look at an example:

#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 <module>
#    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 <module>
#    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!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

I’m trying to make a simplified version of the card game War. In this game, there are two players. Each starts with half of a deck. The players each deal the top card from their decks and whoever has the higher card wins the other player’s cards and adds them to the bottom of his deck. If there is a tie, the two cards are eliminated from play. The game ends when one player runs out of cards.

However, I’m having an issue with the pop argument, in that it gives me an error with «pop from empty list».

How can I fix that?

import random

class Card:
    def __init__(self, value, suit):
        self.value = value
        self.suit = suit
    def __str__(self):
        names = ['Jack', 'Queen', 'King', 'Ace']
        if self.value <= 10:
            return '{} of {}'.format(self.value, self.suit)
        else:
            return '{} of {}'.format(names[self.value-11], self.suit)

class CardGroup:
    def __init__(self, cards = []):
        self.cards = cards
    def shuffle(self):
        random.shuffle(self.cards)

class StandardDeck(CardGroup):
    def __init__(self):
        self.cards = []
        for s in ['Hearts', 'Diamonds', 'Clubs', 'Spades']:
            for v in range(2,15):
                self.cards.append(Card(v, s))
    def deal_out(self, num_cards, num_players):
        deal = [[0 for x in range(num_cards)] for y in range(num_players)]
        for i in range(num_cards):
            for k in range(num_players):
                deal[k][i] = self.cards.pop()
        self.deal = deal

deck = StandardDeck()
deck.shuffle()
print("n===== shuffled deck =====n")

player1_list = []
player2_list = []
for i in range(26):
    p1_temp = deck.deal_out(26, 2)
    player1_list.append(p1_temp)
    p2_temp = deck.deal_out(26, 2)
    if (p2_temp.__init__() == 1):
        player1_list.append(p2_temp)
        player2_list.append(player1_list.pop(0))
    else:
        player2_list.append(p2_temp)


# Card dealt to Player #1
player1_card = player1_list.pop(0)
print("===== player #1 =====")
print("Card dealt to player #1: n", player1_card)
print(player1_list)
    
#Card dealt to Player #2
player2_card = player2_list.pop(0)
print("n===== player #2 =====")
print("Card dealt to player #2: n", player2_card)
print(player2_list)

# Compare the two cards using overloaded operators
if player1_card == player2_card:
    print("Tie: ", player1_card, "and", player2_card,
          "are of equal rank")
elif player1_card > player2_card:
    print("Player #1 wins: ", player1_card, 
          "is of higher rank than", player2_card)
else:
    print("Player #2 wins: ", player2_card, 
        "is of higher rank than", player1_card)
    print()

Answer by Caspian Corona

You’re on the right track.,exporterslist.pop(0) if exporterslist else None,exporterslist.pop(0) if exporterslist else False,

4

if len(exporterslist) > 0

– rapt

Feb 11 ’17 at 18:40

You’re on the right track.

if exporterslist: #if empty_list will evaluate as false.
    importer = exporterslist.pop(0)
else:
    #Get next entry? Do something else?

Answer by Alice Hale

When using the Python list pop() method, if our list is empty, we cannot pop from it anymore. This will raise an IndexError exception.,In this article, we learned how we could pop elements from a list, using the list.pop() method.,The Python list pop() method is used to pop items from Python lists. In this article, we’ll quickly take a look at how we can pop elements from a List using pop().,Since we tried to pop from an empty list, this exception was raised, with the corresponding error message.

my_list.pop()

Answer by Colette Francis

Hello everyone, total python brainlet here, I have been stuck at this problem for hours on end and I seem to never get rid of it. The objective of the code was for the pop() function to stop at the specific number written below but it doesn’t. It just keeps going until it encounters this error.,c never changes inside this loop, which means l is never equal to 0 so the loop goes forever,This is the main code, I have run out of ideas and I have no clue on how to accomplish this without succumbing to frustration. I would greatly appreciate if anyone would give feedback as to how one could solve this.,Thanks for the reply, but are there other alternatives to it? I have tried «if else» and it still receives the error.

Hello everyone, total python brainlet here, I have been stuck at this problem for hours on end and I seem to never get rid of it. The objective of the code was for the pop() function to stop at the specific number written below but it doesn’t. It just keeps going until it encounters this error.

Traceback (most recent call last):
  File "<pyshell#112>", line 11, in <module>
    s.pop()
  File "<pyshell#109>", line 9, in pop
    return self.items.pop()
IndexError: pop from empty list

This is the main code, I have run out of ideas and I have no clue on how to accomplish this without succumbing to frustration. I would greatly appreciate if anyone would give feedback as to how one could solve this.

while True:
	c = 1
	l = 10
	print("What do you want to do with the stack?")
	uinput = int(input("Choices: 1=Push, 2=Pop, 3=Display, 4 =Quit"))
        #fine
	if uinput == 1:
		c+= 1
		s.push(input("Enter want you want to add to the stack."))
        #error cause 
	elif uinput == 2:
		while l != 0:
			l= c - 1
			print(s.pop())
        #fine
	elif uinput == 3:
		if c >= 1:
			print(s.peek())
		else:
			print("Please push")
        #fine
	elif uinput == 4:
		import sys
		sys.exit()

Additional code, if it would help.

class Stack:
	def __init__(self):
		self.items =[]
	def push(self, item):
		self.items.append(item)
	def pop(self):
		return self.items.pop()
	def peek(self):
		return self.items[len(self.items)-1]

Answer by Chana Fischer

You can use the list.pop(index) method to with the optional index argument to remove and return the element at position index from the list.,The list.pop() method removes and returns the last element from an existing list. The list.pop(index) method with the optional argument index removes and returns the element at the position index.,But you can also define the optional index argument. In this case, you’ll remove the element at the given index—a little known Python secret!,The list.pop(index) method to with the optional index argument to remove and return the element at position index from the list. So if you want to remove the first element from the list, simply set index=0 by calling list.pop(0). This will pop the first element from the list.

Here’s a short example:

>>> lst = [1, 2, 3]
>>> lst.pop()
3
>>> lst
[1, 2]

Here’s an example:

>>> customers = ['Alice', 'Bob', 'Ann', 'Frank']
>>> customers.pop(2)
'Ann'
>>> customers
['Alice', 'Bob', 'Frank']
>>> customers.pop(0)
'Alice'
>>> customers
['Bob', 'Frank']

Here’s an example:

>>> primes = [1, 2, 3, 5, 7, 11]
>>> primes.pop(0)
1
>>> primes
[2, 3, 5, 7, 11]

Here’s an example where you want to pop the element 7 from the list and store the result in the variable some_prime.

>>> primes = [1, 2, 3, 5, 7, 11]
>>> some_prime = primes.pop(primes.index(7))
>>> some_prime
7

Here’s another example:

>>> lst = ['a', 'b', 'c', 'd', 'e', 'f']
>>> popped = [lst.pop(0) for i in range(5)]
>>> popped
['a', 'b', 'c', 'd', 'e']
>>> lst
['f']

Here’s another example:

>>> lst = ['a', 'b', 'c', 'd', 'e', 'f']
>>> [lst.pop() for i in range(5)]
['f', 'e', 'd', 'c', 'b']
>>> lst
['a']

I’ve written a short script to evaluate runtime complexity of the pop() method in Python:

import matplotlib.pyplot as plt
import time

y = []
for i in [100000 * j for j in range(5,15)]:
    lst = list(range(i))
    t0 = time.time()
    x = lst.pop(0)
    t1 = time.time()
    y.append(t1-t0)


plt.plot(y)
plt.xlabel("List elements (10**5)")
plt.ylabel("Time (sec)")
plt.show()

Here’s an example that shows how to push three values to the stack and then removing them in the traditional First-In Last-Out (FILO) order of stacks.

>>> stack = []
>>> stack.append(5)
>>> stack.append(42)
>>> stack.append("Ann")
>>> stack.pop()
'Ann'
>>> stack.pop()
42
>>> stack.pop()
5
>>> stack
[]

How can you pop() an element only if the list is not empty in a single line of code? Use the ternary operator in Python lst.pop() if lst else None as follows:

>>> lst = [1, 2, 3]
>>> for i in range(5):
	print(lst.pop() if lst else None)

	
3
2
1
None
None

If you don’t use the ternary operator in this example, Python will throw an IndexError as you try to pop from an empty list:

>>> lst = [1, 2, 3]
>>> for i in range(5):
	print(lst.pop())

	
3
2
1
Traceback (most recent call last):
  File "<pyshell#15>", line 2, in <module>
    print(lst.pop())
IndexError: pop from empty list

Why? Because the iterator is created only once in the loop definition and it will stubbornly give you the indices it prepared in the beginning. If the loop changes, the indices of the elements change, too. But the iterator doesn’t adapt the indices to account for those changes. Here’s an example:

>>> lst = list(range(10))
>>> for i in range(len(lst)):
	lst.pop(i)

	
0
2
4
6
8
Traceback (most recent call last):
  File "<pyshell#20>", line 2, in <module>
    lst.pop(i)
IndexError: pop index out of range

To remove an element from the list, use the list.remove(element) method you’ve already seen previously:

>>> lst = ["Alice", 3, "alice", "Ann", 42]
>>> lst.remove("Ann")
>>> lst
['Alice', 3, 'alice', 42]

If you’re trying to remove element x from the list but x does not exist in the list, Python throws a Value error:

>>> lst = ['Alice', 'Bob', 'Ann']
>>> lst.remove('Frank')
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    lst.remove('Frank')
ValueError: list.remove(x): x not in list

Per default, the pop() method removes the last element from the list and returns the element.

>>> lst = ['Alice', 'Bob', 'Ann']
>>> lst.pop()
'Ann'
>>> lst
['Alice', 'Bob']

But you can also define the optional index argument. In this case, you’ll remove the element at the given index—a little known Python secret!

>>> lst = ['Alice', 'Bob', 'Ann']
>>> lst.pop(1)
'Bob'
>>> lst
['Alice', 'Ann']

The clear() method simply removes all elements from a given list object.

>>> lst = ['Alice', 'Bob', 'Ann']
>>> lst.clear()
>>> lst
[]
  • Use del lst[index] to remove the element at index.
  • Use del lst[start:stop] to remove all elements in the slice.
>>> lst = list(range(10))
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del lst[5]
>>> lst
[0, 1, 2, 3, 4, 6, 7, 8, 9]
>>> del lst[:4]
>>> lst
[4, 6, 7, 8, 9]

You can also define a condition such as all odd values x%2==1 in the context part by using an if condition. This leads us to a way to remove all elements that do not meet a certain condition in a given list.

>>> lst = list(range(10))
>>> lst_new = [x for x in lst if x%2]
>>> lst_new
[1, 3, 5, 7, 9] 

Answer by Esperanza Weber

IndexError: pop from empty list,span_stack may be empty,@beniwohli Thanks
I use the flask, not used asynchronous framework.,
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

def end_span(self, skip_frames):
        span = self.span_stack.pop()

Answer by Mazikee Foley

without_empty_strings = [string for string in a_list if string != ""]

Answer by Jaylah Sutton

(if you have the negative numbers handled already that is, else try to convert to integer and catch the ValueError)

My code:

from StackClass import Stack


def postfixEval(postfix):
    os = Stack()

    tokenList = postfix

    for token in tokenList:
        if token in "0123456789":
            os.push(int(token))
        else:
            op2 = os.pop()
            op1 = os.pop()
            result = doMath(token,op1,op2)
            os.push(result)
    return os.pop()

def doMath(op, op1, op2):
    if op == "*":
        return op1 * op2
    elif op == "/":
        return op1 / op2
    elif op == "+":
        return op1 + op2
    else:
        return op1 - op2



def pres(p):
    if p is '(':
        return 0
    elif p is '+' or '-':
        return 1
    elif p is '*' or '/':
        return 2
    else:
        return 99

def read(p):
    if p is '(':
        return left
    elif p is ')':
        return right
    elif p is '+' or p is '-' or p is '*' or p is '%' or p is '/':
        return operator
    elif p is ' ':
        return empty    
    else :
        return operand                          




def infixtopostfix(infixexp):

    for i in infixexp :
        type = read(i)
        if type is left :
            outlst.append(i)
        elif type is right :
            next = outlst.pop()
            while next is not '(':
                postfix.append(next)
                next = outlst.pop()
        elif type is operand:
            postfix.append(i)
        elif type is operator:
            p = pres(i)
            while len(outlst) is not 0 and p <= pres(outlst[-1]) :
                postfix.append(outlst.pop())
            outlst.append(i)
        elif type is empty:
            continue

    while len(outlst) > 0 :
        postfix.append(outlst.pop())
    return " ".join(postfix)












#MAIN PROGRAM


while True:



    postfix = []
    outlst = []
    operator = -10
    operand = -20
    left = -30
    right = -40
    empty = -50


    infixexp = raw_input("nEnter the infix notation : ")
    ifx = infixexp.split()
    showpfx = infixtopostfix(ifx)

    print "nIt's postfix notation is n"
    print(showpfx) 

    print "nThe answer to the postfix notation is: n"
    pfx = showpfx.split()
    print postfixEval(pfx)  



    choice = raw_input("nDo you want to continue?<1-Yes/0-No>: ")

    if choice == '0':
        break

This works on ( 1 + 3 ) * 5 but gives this error on ( 500 + 500 ) * 1000 :

> Traceback (most recent call last):   File "practice.py", line 117, in
> <module>
>     print postfixEval(pfx)   File "practice.py", line 13, in postfixEval
>     op2 = os.pop()   File "C:Python27StackClass.py", line 16, in pop
>     return self.items.pop() IndexError: pop from empty list

Answer by Margot Tate

So, we can conclude that while performing Python list pop() method on an empty list, an IndexError is thrown.,Similar to the previous section, when we try to perform the Python List pop() method on an empty list, we face the same IndexError. For example:,While using the Python list pop() method, we encounter an IndexError if the index passed to the method is greater than the list length.,Hence, we must check before we apply the pop() method, that the list we are dealing with is not empty. A simple length check can solve our problem.

#pop() method syntax in Python
pop(index)    

Description

I am getting a pop from empty list error from the warnings.filers.pop(0) call in get_params(). I am using Dask to parallelize the computation of fitting a bunch of MeanShift objects. I only get this error on one machine (a remote linux machine), but it works fine on my home compute (running ubuntu 14)

Steps/Code to Reproduce

Expected Results

Should just fit the MeanShifts and move on

Actual Results

Traceback (most recent call last):
File «tda_profile.py», line 34, in
_tda.fit(train_features, train_targets)
File «/home/ben/tda/tda_parallel_test.py», line 652, in fit
fits = fits.compute()
File «/home/ben/anaconda3/lib/python3.5/site-packages/dask/base.py», line 86, in compute
return compute(self, *_kwargs)[0]
File «/home/ben/anaconda3/lib/python3.5/site-packages/dask/base.py», line 179, in compute
results = get(dsk, keys, *_kwargs)
File «/home/ben/anaconda3/lib/python3.5/site-packages/dask/threaded.py», line 57, in get
**kwargs)
File «/home/ben/anaconda3/lib/python3.5/site-packages/dask/async.py», line 484, in get_async
raise(remote_exception(res, tb))
dask.async.IndexError: pop from empty list

Traceback

File «/home/ben/anaconda3/lib/python3.5/site-packages/dask/async.py», line 267, in execute_task
result = execute_task(task, data)
File «/home/ben/anaconda3/lib/python3.5/site-packages/dask/async.py», line 249, in execute_task
return func(*args2)
File «/home/ben/anaconda3/lib/python3.5/site-packages/sklearn/cluster/mean_shift
.py», line 391, in fit
cluster_all=self.cluster_all, n_jobs=self.n_jobs)
File «/home/ben/anaconda3/lib/python3.5/site-packages/sklearn/cluster/mean_shift
.py», line 191, in mean_shift
(seed, X, nbrs, max_iter) for seed in seeds)
File «/home/ben/anaconda3/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py», line 800, in call
while self.dispatch_one_batch(iterator):
File «/home/ben/anaconda3/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py», line 658, in dispatch_one_batch
self._dispatch(tasks)
File «/home/ben/anaconda3/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py», line 566, in _dispatch
job = ImmediateComputeBatch(batch)
File «/home/ben/anaconda3/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py», line 180, in init
self.results = batch()
File «/home/ben/anaconda3/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py», line 72, in call
return [func(_args, *_kwargs) for func, args, kwargs in self.items]
File «/home/ben/anaconda3/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py», line 72, in
return [func(_args, *kwargs) for func, args, kwargs in self.items]
File «/home/ben/anaconda3/lib/python3.5/site-packages/sklearn/cluster/mean_shift
.py», line 75, in _mean_shift_single_seed
bandwidth = nbrs.get_params()[‘radius’]
File «/home/ben/anaconda3/lib/python3.5/site-packages/sklearn/base.py», line 227, in get_params
warnings.filters.pop(0)

Versions

import platform; print(platform.platform())
Linux-3.10.0-327.el7.x86_64-x86_64-with-centos-7.2.1511-Core
import sys; print(«Python», sys.version)
Python 3.5.2 |Anaconda 4.1.1 (64-bit)| (default, Jul 2 2016, 17:53:06)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
import numpy; print(«NumPy», numpy.version)
NumPy 1.11.1
import scipy; print(«SciPy», scipy.version)
SciPy 0.17.1
import sklearn; print(«Scikit-Learn», sklearn.version)
Scikit-Learn 0.17.1

Annoying «IndexError: pop from empty list»

Hello everyone, total python brainlet here, I have been stuck at this problem for hours on end and I seem to never get rid of it. The objective of the code was for the pop() function to stop at the specific number written below but it doesn’t. It just keeps going until it encounters this error.

Traceback (most recent call last):
  File "<pyshell#112>", line 11, in <module>
    s.pop()
  File "<pyshell#109>", line 9, in pop
    return self.items.pop()
IndexError: pop from empty list

This is the main code, I have run out of ideas and I have no clue on how to accomplish this without succumbing to frustration. I would greatly appreciate if anyone would give feedback as to how one could solve this.

while True:
	c = 1
	l = 10
	print("What do you want to do with the stack?")
	uinput = int(input("Choices: 1=Push, 2=Pop, 3=Display, 4 =Quit"))
        #fine
	if uinput == 1:
		c+= 1
		s.push(input("Enter want you want to add to the stack."))
        #error cause 
	elif uinput == 2:
		while l != 0:
			l= c - 1
			print(s.pop())
        #fine
	elif uinput == 3:
		if c >= 1:
			print(s.peek())
		else:
			print("Please push")
        #fine
	elif uinput == 4:
		import sys
		sys.exit()

Additional code, if it would help.

class Stack:
	def __init__(self):
		self.items =[]
	def push(self, item):
		self.items.append(item)
	def pop(self):
		return self.items.pop()
	def peek(self):
		return self.items[len(self.items)-1]

Понравилась статья? Поделить с друзьями:
  • Poo54 ошибка ситроен
  • Poo37 код ошибки
  • Poo36 ошибка форд
  • Poo36 ошибка ваз
  • Poo31 ошибка тойота