UNIT-II SET in python
UNIT-II SET in python
In Python, a set is a built-in data type that represents an unordered collection of unique items. Sets
are useful for storing multiple items in a single variable and performing operations like union,
intersection, and difference. Here’s a quick overview of how to work with sets in Python:
Creating a Set
We can create a set using curly braces `{}` or the `set()` function.
my_set = {1, 2, 3}
OUTPUT
{1, 2, 3}
Basic Operations
Add an Element:
Useadd()
Remove an Element:
Check Membership:
if 1 in my_set:
Set Operations
Union:
set_b = {3, 4, 5}
Intersection:
Difference:
Find elements in one set that are not in the other using `-` or the `difference()` method
Symmetric Difference:
Find elements in either set but not in both using `^` or the `symmetric_difference()` method
Length:
Use len()
Clear:
Important Notes
- Sets are unordered, meaning the elements do not have a defined order.
Example
Create a set
Add a fruit
fruits.add('grape')
# Remove a fruit
fruits.discard('banana')
# Check membership
if 'apple' in fruits: