I'm currently learning Python and I am just wondering in what situation one would use .remove()
rather than .discard()
when removing values from a set
. Since .discard()
does not raise an error when removing a element form a set if the element isn't present wouldn't it be the better one to use?
Errors are raised to be caught and processed. They are not annoyances or hurdles. They are tools to identify conceptual errors, or to indicated unexpected behavior that one needs to pay attention to, or to deal with parts of the system that one does not have control over, or to use to control the flow of the code where the python doctrine says „fail rather than test“ i.e. let the code raise exceptions you expect rather than testing with if statements.
In the case of .discard()
and .remove()
: .discard()
calls .remove()
silently catches the exception in case the value was not there and silently returns. It’s a shortcut for a silent .remove()
. It might be suitable for your special use-case. Other use-cases might require an exception to be raised when the value does not exist.
So .remove()
is the general case that gives the developer control over the exception and .discard()
is just a special use case where the developer does not need to catch that execration.
Like you have said .discard() method does not raise any error on the other hand .remove() method does. So it depends on the situation. You can use discard method if you do not want to catch the ValueError do to something else with try-except blocks.
Well each of it has its own use in different cases.
For example you want to create a program that takes input from user and can add, remove or change data. Then when the user chooses the remove option and suppose it enters a value that is not in data, you would want to tell him that it is not in the data ( most probably using the try - except
), you would like to use the remove() function rather than .discard()
© 2022 - 2024 — McMap. All rights reserved.
.discard
. Exceptions exist to tell you something isn't right, and often (I would say usually) when you want to remove an element from a container, you are assuming it is in the container – Headlight.remove()
is more general since you can always ignore the error in the first case. – Violaviolable