Python Set Operations Explained: From Theory to Real-Time Applications
![Image](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvdu44eT6DZ9hMVhjEvxO7i-WgF2nNAGZqEc0pcUlr-svIbAEaI6ei3INwtMEop65UKtseaxWQTle6JmmwGW9HrwwEq9nMjpAZ1lz5l8VLQchum9zw3Nu-29kAFoqSSwGljCTc36QJAkUE5UmUuB9VWeX3_S3Qm6dNMcR3VvlbqtBOl9PPcQKBTmF-1N0u/w320-h180/Python%20Set%20Operations.jpg)
Python program:
#Prints all the Set items
food = {"pasta", "burger", "hot dog", "pizza"}
print(food)
# Prints the Set items without pasta
food.discard("pasta")
print(food)
# Prints the Set items without burger and pasta
food.remove("burger")
print(food)
# The next two lines try to remove an item that isn't in the set!
food.discard("pasta") # this will not report an error
food.remove("pasta") # this will report an error
The output:
{'pasta', 'burger', 'pizza', 'hot dog'}
{'burger', 'pizza', 'hot dog'}
{'pizza', 'hot dog'}
Traceback (most recent call last):
File "main.py", line 12, in <module>
food.remove("pasta") # this will report an error
KeyError: 'pasta'
** Process exited - Return Code: 1 **
Press Enter to exit terminal
Related
Comments
Post a Comment
Thanks for your message. We will get back you.