0% found this document useful (0 votes)
20 views

UNIT-II SET in python

Sets in python

Uploaded by

Raja shree
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

UNIT-II SET in python

Sets in python

Uploaded by

Raja shree
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

SET

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.

# Using curly braces

my_set = {1, 2, 3}

# Using the set() function

my_set_from_list = set([1, 2, 2, 3]) # Duplicates are removed

OUTPUT

{1, 2, 3}

Basic Operations

Add an Element:

Useadd()

my_set.add(4) # my_set is now {1, 2, 3, 4}

Remove an Element:

Use remove() or discard()

my_set.remove(2) # Raises KeyError if 2 is not present

my_set.discard(3) # Does not raise an error if 3 is not present

Check Membership:

Use the in keyword

if 1 in my_set:

print("1 is in the set")

Set Operations

Union:

Combine two sets using `|` or the `union()` method


set_a = {1, 2, 3}

set_b = {3, 4, 5}

union_set = set_a | set_b # {1, 2, 3, 4, 5}

Intersection:

Find common elements using &or the intersection() method

intersection_set = set_a & set_b # {3}

Difference:

Find elements in one set that are not in the other using `-` or the `difference()` method

difference_set = set_a - set_b # {1, 2}

Symmetric Difference:

Find elements in either set but not in both using `^` or the `symmetric_difference()` method

symmetric_diff_set = set_a ^ set_b # {1, 2, 4, 5}

Other Useful Methods

Length:

Use len()

print(len(my_set)) # Number of elements in the set

Clear:

Remove all elements from the set

my_set.clear() # my_set is now an empty set

Important Notes

- Sets do not allow duplicate elements.

- Sets are unordered, meaning the elements do not have a defined order.

- The elements of a set must be immutable (e.g., numbers, strings, tuples).

Example

Here’s a simple example that puts everything together:

Create a set

fruits = {'apple', 'banana', 'orange'}

Add a fruit

fruits.add('grape')
# Remove a fruit

fruits.discard('banana')

# Check membership

if 'apple' in fruits:

print("Apple is in the set.")

# Perform set operations (Union)

citrus = {'orange', 'lemon', 'lime'}

all_fruits = fruits | citrus # Union

print(all_fruits) # Output: {'apple', 'grape', 'orange', 'lemon', 'lime'}

You might also like