English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial básico Python

Controle de fluxo Python

Função do Python

Tipos de Dados do Python

Operações de arquivos Python

Objetos e classes Python

Data e hora Python

Conhecimento avançado Python

Manual de referência Python

Uso e exemplo do pop() da lista Python

Python list methods

O método pop() remove o item no índice especificado da lista e retorna o item removido.

A sintaxe do método pop() é:

list.pop(index)

Parâmetro do pop()

  • O método pop() aceita um único parâmetro (índice).

  • Os parâmetros passados para o método são opcionais. Se não forem passados, o índice padrão-1as a parameter (the index of the last item).

  • If the index passed to this method is out of range, it will throwIndexError: pop index out of rangeException.

pop() return value

The pop() method returns the item at the given index and removes it from the list.

Example1: Extract the item at the given index from the list

# Programming language list
languages = ['Python', 'Java', 'C'++', 'French', 'C'
# Delete and return the fourth item
return_value = languages.pop()3)
print('Return value:', return_value)
# Updated list
print('Updated list:', languages)

Output result

Return value: French
Updated list: ['Python', 'Java', 'C'++', 'C'

Note: Python indexes start from 0, not1.

If you need to pop the item at4 elementselements, you need to set3passed to the pop() method.

Example2:pop() without index, and negative index

# Programming language list
languages = ['Python', 'Java', 'C'++', 'Ruby', 'C'
# Delete and return the last item
print('When no index is passed:') 
print('Return value:', languages.pop())
print('Updated list:', languages)
# Delete and return the last item
print('\nParameter for-1:) 
print('Return value:', languages.pop())-1))
print('Updated list:', languages)
# Delete and return the third last item
print('\nParameter for-3:) 
print('Return value:', languages.pop())-3))
print('Updated list:', languages)

Output result

When no index is passed:
Return value: C
Updated list: ['Python', 'Java', 'C'++', 'Ruby'
The parameter is-1:
Return value: Ruby
Updated list: ['Python', 'Java', 'C'++'
The parameter is-3:
Return value: Python
Updated list: ['Java', 'C'++'

If you need to remove the given item from the list, you can useremove() method.

And, you can use the del statementRemove items or slices from the list.

Python list methods