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

Introduction to Sets in Python

Sets in Python are unordered collections of unique elements that can be created using curly braces or the set() constructor. They support various operations such as adding, removing elements, and performing set algebra like union and intersection. Key features include mutability, automatic duplicate removal, and the inability to index or slice sets.

Uploaded by

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

Introduction to Sets in Python

Sets in Python are unordered collections of unique elements that can be created using curly braces or the set() constructor. They support various operations such as adding, removing elements, and performing set algebra like union and intersection. Key features include mutability, automatic duplicate removal, and the inability to index or slice sets.

Uploaded by

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

Introduction to Sets in

Python
Sets are unordered collections of unique elements for fast data
handling.

They are mutable and automatically remove duplicate entries.

Create sets using curly braces or the set() constructor.

by Raymart Faller
Creating Sets in Python
Empty Set
Use set() to create an empty set; not curly braces.

From List
Convert list with duplicates to set to keep unique items.

From String
Create set of unique characters from a string.

Set Comprehension
Generate sets dynamically with conditions.
Basic Set Operations
Membership Test Length
Check if element exists in a set quickly. Count how many unique elements the set contains.

Iteration Not Indexable


Access each element, order is arbitrary since sets Sets don't support indexing or slicing operations.
are unordered.
Adding and Removing Elements
add(element) update(iterable)

Add a single new item to the set. Add multiple items from list or other iterable.

Example: my_set.add(4) Example: my_set.update([4,5,6])

remove(element) discard(element)

Remove an element; raises error if missing. Remove an element if present; no error if missing.

Example: my_set.remove(2) Example: my_set.discard(7)

The pop() method removes and returns an arbitrary element.


Set Algebra: Union and
Intersection

Union Intersection
Combine two sets with no Get common elements with & or
duplicates using | or union(). intersection().
Set Algebra: Difference & Symmetric
Difference
Difference (-) Symmetric Difference (^)

Elements in one set but not the other. Elements in either set, but not both.

Example: set1 - set2 Example: set1 ^ set2

You might also like