English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode pop() supprime l'élément à l'index donné dans la liste et renvoie l'élément supprimé.
La syntaxe de la méthode pop() est :
list.pop(index)
La méthode pop() utilise un seul paramètre (index).
Les paramètres passés à la méthode sont optionnels. Si aucun n'est passé, l'index par défaut est utilisé.-1as the parameter (the index of the last item) to be passed.
If the index passed to this method is not within the range, it will throwIndexError: pop index out of rangeException.
The pop() method returns the item existing at the given index. And it deletes the item 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 after being updated print('Updated list:', languages)
Output result
Return value: French Updated list: ['Python', 'Java', 'C'++', 'C'
Note: Python's index starts from 0, not1.
If you need to pop the item at4 numberelements, you need to set3is passed to the pop() method.
# 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 is-1:') print('Return value:', languages.pop())-1)) print('Updated list:', languages) # Delete and return the third last item print('\nParameter is-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.