« Programmation Python/Ensembles » : différence entre les versions

Contenu supprimé Contenu ajouté
Ligne 103 :
</source>
 
== Retrait de membre ==
==Removing Items==
 
Il existe quatre fonctions pour retirer des membres à un ensemble :
There are three functions which remove individual items from a set, called pop, remove, and discard. The first, pop, simply removes an item from the set. Note that there is no defined behavior as to which element it chooses to remove.
# "pop" : retire un membre non précisé.
# "remove" : retire le membre existant précisé.
# "discard" : retire un membre précisé.
# "clear" : retire tous les éléments.
 
<source lang="python">
Ligne 113 ⟶ 117 :
>>> s
set([2,3,4,5,6])
</source>
 
We also have the "remove" function to remove a specified element.
 
<source lang="python">
>>> s.remove(3)
>>> s
set([2,4,5,6])
</source>
 
However, removing a item which isn't in the set causes an error.
 
<source lang="python">
>>> s.remove(9)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 9
</source>
 
If you wish to avoid this error, use "discard." It has the same functionality as remove, but will simply do nothing if the element isn't in the set
 
We also have another operation for removing elements from a set, clear, which simply removes all elements from the set.
 
<source lang="python">
>>> s.clear()
>>> s