Sets
Sets in Python are another type of collection. Unlike lists and tuples, sets are unordered and only contain unique elements. This means sets do not record the position of elements, and duplicates are automatically removed when creating a set.
To define a set, curly brackets {} are used, with elements separated by commas. For example:
set_A = {'apple', 'banana', 'orange', 'banana'}
After creating this set, notice that the duplicate element 'banana' is removed automatically.
You can also convert a list to a set using the set() function, which performs type casting. For
instance:
my_list = ['apple', 'banana', 'orange', 'banana']
my_set = set(my_list)
This will result in my_set containing only unique elements.
Set operations can be used to modify sets. For example, to add an item to a set, you can use the add() method:
set_A.add('NSYNC')
To remove an item from a set, the remove() method is used:
set_A.remove('NSYNC')
To check if an element is present in a set, you can use the in keyword:
print('AC/DC' in set_A) # Output: True
print('Who' in set_A) # Output: False
Mathematical set operations can also be performed on sets. For instance:
- Intersection: Finds elements that are common between two sets. In Python, the
&operator is used. - Union: Combines elements from both sets. In Python, the
|operator is used. - Subset: Checks if one set is entirely contained within another set. In Python, the
issubset()method is used.
For example: set_one = {'AC/DC', 'Queen', 'Pink Floyd'} set_two = {'AC/DC', 'Led Zeppelin', 'Metallica'} intersection_set = set_one & set_two union_set = set_one | set_two print(intersection_set) # Output: {'AC/DC'} print(union_set) # Output: {'AC/DC', 'Queen', 'Pink Floyd', 'Led Zeppelin', 'Metallica'} print(set_one.issubset(union_set)) # Output: True Sets provide efficient ways to perform operations like finding common elements, combining sets, and checking relationships between sets.
Comments
Post a Comment