Sets in Python
Sets in Python
Sets in Python are unordered collections of unique elements in Python. They are similar to lists but do not allow duplicate elements. Sets are defined using curly braces {}
or the set()
constructor.
Key Characteristics:
- Unordered: Elements in a set do not have a specific order.
- Unique Elements: Sets cannot contain duplicate elements.
- Mutable: Sets can be modified by adding or removing elements.
- Iterable: You can iterate over the elements of a set using a loop.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the curly braces {}. Python also provides the set() method, which can be used to create the set by the passed sequence.
Example 1: Using curly braces
- Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
- print(Days)
- print(type(Days))
- print("looping through the set elements ... ")
- for i in Days:
- print(i)
Output:
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'} <class 'set'> looping through the set elements ... Friday Tuesday Monday Saturday Thursday Sunday Wednesday
Accessing Elements:
You cannot access elements in a set by index, as they are unordered. However, you can check if an element exists in a set using the in
operator:
if 3 in my_set:
print("3 is in the set")
Adding and Removing Elements:
You can add elements to a set using the add()
method and remove elements using the remove()
method.
my_set.add(6)
my_set.remove(2)
Set Operations:
Sets support various operations, including:
- Union:
|
operator orunion()
method: Creates a new set containing all elements from both sets. - Intersection:
&
operator orintersection()
method: Creates a new set containing elements common to both sets. - Difference:
-
operator ordifference()
method: Creates a new set containing elements present in the first set but not in the second. - Symmetric Difference:
^
operator orsymmetric_difference()
method: Creates a new set containing elements that are in either set, but not both.
A Python set is the collection of the unordered items. Each element in the set must be unique, immutable, and the sets remove the duplicate elements. Sets are mutable which means we can modify it after its creation.
Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we cannot directly access any element of the set by the index. However, we can print them all together, or we can get the list of elements by looping through the set.
Comments
Post a Comment