As happens in gangs, sometimes members disappear. Let's say that Colonel Sanders has had enough of the McDonald's Gang encroaching on his turf. Se he sets loose the hound from hell, aka the Taco Bell dog. The end result is the demise of the Hamburglar. Rubble Rubble. There are three ways Ronald can remove the Hamburglar from the Set. Here they are. Pop Goes the Greaseball The first method for deleting an element from a Set is the pop. It simply removes an element from the set. /usr/local/bin/python mcdonaldgang = Set (['Grimace', 'Hamburglar', 'Mayor Mccheese', 'Burger King', 'Wendy', 'Fry Guy']) mcdonaldgang.pop() The pop method may or may not remove the Hamburglar. This is because the pop method knows no rules. It deletes who it wants, when it wants. It picks an element at random, and deletes them. Period. If you want to specifically remove the Hamburglar, you might want to try out Pop's more lawful cousin, the Remove function: /usr/local/bin/python mcdonaldgang = Set (['Grimace', 'Hamburglar', 'Mayor Mccheese', 'Burger King', 'Wendy', 'Fry Guy']) mcdonaldgang.remove('Hamburglar') print mcdonaldgang The Remove function will remove the element that you specify. When we print out our list it will be: Grimace Wendy Mayor Mccheese Fry Guy Burger King The only problem with the Remove function is that if you make a typo or the value does not exist in the Set, an error will be returned. To overcome this problem, simply use our third function, the Discard function. /usr/local/bin/python mcdonaldgang = Set (['Grimace', 'Hamburglar', 'Mayor Mccheese', 'Burger King', 'Wendy', 'Fry Guy']) mcdonaldgang.discard('Hamburglar') print mcdonaldgang This gives us the same result: Grimace Wendy Mayor Mccheese Fry Guy Burger King Lastly, if we wanted to remove all of the data in a Set, we can use the Clear function. usr/local/bin/python mcdonaldgang = Set (['Grimace', 'Hamburglar', 'Mayor Mccheese', 'Burger King', 'Wendy', 'Fry Guy']) mcdonaldgang.clear()
blog comments powered by Disqus |
|
|
|
|
|
|
|