I initially defined a set using destinations={"x",}
. Then I tried to remove something using destinations=destinations.discard("x")
. However, the terminal says AttributeError: 'NoneType' object has no attribute 'discard'
when I try to run it. It seems that it is not yet a set. I included a comma with the braces when initializing it and at least it should be a string. What am I doing wrong?
Quamrana's comment answers the essence of your question, but to break it down:
destinations={"x","y",} #"y" added for the sake of demonstration
destinations = destinations.discard("x")
print(destinations) # Output = '' i.e. no output
If you see type(destinations)
, it will output as <class 'NoneType'>
That's because discard (similar to many other methods) returns a NoneType object. (The same is true for other methods like list.append(). However, note that is this not true for all methods. For example dict.pop(key) returns a non-NoneType Object.)
Now for the proper way to do it:
destinations={"x","y",} #"y" added for the sake of demonstration
destinations.discard("x")
print(destinations) # Output: {'y'}
If you see type(destinations)
, it will output as <class 'set'>
Interestingly, if you were to reassign the variable, your original set would still be affected.
destinations = {"x","y"}
new_set = destinations
new_set.discard('x')
print(new_set) # output = {'y'}
print(destinations) # output = {'y'}
Since you're learning CS50, i think David will cover this at some point when teaching lists: Have fun learning :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.