python basics sets

Save (0)
Close

Recommended

Description

In Python, a set is a collection of unique elements. Sets are distinguished from lists, tuples, and dictionaries in that they do not contain any duplicates.

Here are some basic operations that can be performed with Python sets:

1. Creating a Set: A set can be created by enclosing a comma-separated list of elements in curly braces {}. An empty set is created by calling the built-in set() function. Here is an example:

# create a set
my_set = {3, 5, 7, 11}

# create an empty set
empty_set = set()

2. Adding Elements to a Set: Elements can be added to a set using the `add()` method. Here is an example:

# add an element to a set
my_set.add(13)

3. Removing Elements from a Set: Elements can be removed from a set using the `remove()` method. If the element is not in the set, a `KeyError` will be raised. To avoid this, the `discard()` method can be used instead. Here are some examples:

# remove an element from a set
my_set.remove(5)

# remove an element using discard()
my_set.discard(7)

# attempt to remove a non-existent element
my_set.remove(17) # KeyError
my_set.discard(17) # no error

4. Set Operations: Sets can be combined, intersected, and subtracted using various mathematical operations. Here are some examples:

# create two sets
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# union of two sets
union_set = set1 | set2

# intersection of two sets
intersection_set = set1 & set2

# difference of two sets
difference_set = set1 – set2

In addition to these basic operations, sets also support the usual assortment of container operations, such as `in` and `len()`. Overall, sets are a powerful and versatile data type in Python that are useful for a wide range of programming tasks.