Set in Python with Examples

In Python, a set is a collection of unique elements with no specific order. The elements in a set are enclosed in curly braces {}, separated by commas.

Here’s an example of how to create a set:

my_set = {1, 2, 3, 4, 5}

This creates a set containing the elements 1, 2, 3, 4, and 5.

Here are some key characteristics of sets in Python:

  • Sets are unordered, meaning the elements are not stored in any particular order.
  • Sets only contain unique elements. If you try to add a duplicate element to a set, it will be ignored.
  • Sets can contain elements of different data types (e.g., integers, strings, floats).

Here are some examples of operations that can be performed on sets:

# Adding elements to a set
my_set.add(6)
my_set.update({7, 8})

# Removing elements from a set
my_set.discard(5)
my_set.remove(4)

# Set operations (union, intersection, difference)
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union_set = set1.union(set2)
intersection_set = set1.intersection(set2)
difference_set = set1.difference(set2)

In the code above, we add elements to my_set, remove elements from it, and perform set operations on two different sets (set1 and set2). The resulting sets are stored in new variables union_set, intersection_set, and difference_set.

Overall, sets are a powerful and useful data structure in Python, particularly for working with collections of unique elements

.

Leave a Comment