In Python, a set is an unordered and mutable collection of unique elements. Here are some examples illustrating the use of sets:
1. Creating Sets:
```python
fruits_set = {'apple', 'banana', 'orange'}
mixed_set = {1, 'hello', 3.14, True}
```
2. Adding and Removing Elements:
```python
numbers_set = {1, 2, 3, 4, 5}
numbers_set.add(6) # Adding a single element
numbers_set.update({7, 8, 9}) # Adding multiple elements
numbers_set.remove(3) # Removing a specific element
```
3. Set Operations:
```python
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union_set = set1.union(set2) # {1, 2, 3, 4, 5, 6}
intersection_set = set1.intersection(set2) # {3, 4}
difference_set = set1.difference(set2) # {1, 2}
```
4. Checking Membership:
```python
colors = {'red', 'green', 'blue'}
is_red_present = 'red' in colors # True
is_yellow_present = 'yellow' in colors # False
```
5. Set Methods:
```python
numbers_set = {1, 2, 3, 4, 5}
numbers_set.pop() # Remove and return an arbitrary element
numbers_set.clear() # Remove all elements from the set
```
6. Frozensets:
```python
frozen_set = frozenset([1, 2, 3, 4])
```
Frozensets are immutable sets, meaning once created, their elements cannot be changed or modified.
These examples cover basic set operations and usage in Python. Sets are useful when dealing with collections of unique elements, and they provide efficient methods for set operations.
0 Comments