Sets are another standard data type in Python. They are used to store multiple items in a single variable and are one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary.
What’s special about sets is that they are unordered and do not allow duplicate values. Here’s how you can use them:
1. Create a Set:
You can define a set by placing a comma-separated sequence of items in curly braces `{}`.
```
my_set = {1, 2, 3, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5}
```
1. Add Elements to a Set:
You can use the `add()` method to add a single element to the set and the `update()` method to add multiple items.
```
my_set.add(6)
print(my_set) # Output: {1, 2, 3, 4, 5, 6}
my_set.update([7, 8, 9])
print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9}
```
1. Remove Elements from a Set:
You can use the `remove()` or `discard()` method to remove an item. The `remove()` method will raise an error if the item does not exist in the set, the `discard()` method will not.
```
my_set.remove(9)
print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
my_set.discard(8)
print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7}
```
1. Set Operations:
You can perform typical set operations like union, intersection, difference, and symmetric difference.
```
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # Output: {3}
print(set1.difference(set2)) # Output: {1, 2}
print(set1.symmetric_difference(set2)) # Output: {1, 2, 4, 5}
```
1. Check if item exists:
To check if an item exists in a set, you can use the `in` keyword.
```
my_set = {1, 2, 3, 4, 5}
print(3 in my_set) # Output: True
print(6 in my_set) # Output: False
```
Note: Sets are mutable. But since they are unordered, indexing has no meaning. Hence, we cannot access or change an element of a set using indexing or slicing.