Python Sets



In Python, sets are an unordered collection of unique elements. They are useful for various operations, such as removing duplicates from a list, testing membership, and performing set operations like union, intersection, and difference. Here's a basic lesson on sets in Python:

### Creating Sets:

You can create a set in Python using curly braces `{}` or the `set()` constructor:

```python
# Using curly braces
my_set = {1, 2, 3, 4, 5}

# Using set() constructor
another_set = set([4, 5, 6, 7, 8])
```

### Basic Operations:

#### 1. Adding Elements:

You can add elements to a set using the `add()` method:

```python
my_set.add(6)
```

#### 2. Removing Elements:

Use the `remove()` method to remove an element. If the element is not present, it raises a `KeyError`. Alternatively, you can use `discard()` to remove an element without raising an error if it's not present.

```python
my_set.remove(3)
# or
my_set.discard(3)
```

#### 3. Set Operations:

Python provides several set operations like union (`|`), intersection (`&`), difference (`-`), and symmetric difference (`^`):

```python
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}

# Union
union_set = set1 | set2

# Intersection
intersection_set = set1 & set2

# Difference
difference_set = set1 - set2

# Symmetric Difference
symmetric_difference_set = set1 ^ set2
```

### Set Methods:

#### 1. `union()`, `intersection()`, `difference()`, `symmetric_difference()`:

These methods provide alternatives to the set operators mentioned above:

```python
union_set = set1.union(set2)
intersection_set = set1.intersection(set2)
difference_set = set1.difference(set2)
symmetric_difference_set = set1.symmetric_difference(set2)
```

#### 2. `issubset()` and `issuperset()`:

Check if one set is a subset or superset of another:

```python
is_subset = set1.issubset(set2)
is_superset = set1.issuperset(set2)
```

### Membership Test:

You can check if an element is present in a set using the `in` keyword:

```python
if 3 in my_set:
    print("3 is in the set.")
```

### Frozen Sets:

A `frozenset` is an immutable version of a set. Once created, you cannot add or remove elements from it:

```python
frozen_set = frozenset([1, 2, 3, 4])
```

Sets in Python are versatile and can be handy in various situations where you need to work with unique elements or perform set operations efficiently.


Contact us for software training, education or development










 

Post a Comment

0 Comments