Sets
Unordered collection of items.
Every set element is
- Unique (no duplicates)
- Must be immutable
Creating a Set
- Created by enclosing elements within {curly} brackets.
- Each item is separated by a comma.
Code
PYTHON
Output
Need not be in the same order as defined.
No Duplicate Items
Sets contain unique elements
Code
PYTHON
Output
Immutable Items
Set items must be immutable. As List is mutable, Set cannot have list as an item.
Code
PYTHON
Output
Creating Empty Set
We use
set()
to create an empty set.Code
PYTHON
Output
Converting to Set
set(sequence)
takes any sequence as argument and converts to set, avoiding duplicates List to Set
Code
PYTHON
Output
String to Set
Code
PYTHON
Output
Tuple to Set
Code
PYTHON
Output
Accessing Items
As sets are unordered, we cannot access or change an item of a set using
- Indexing
- Slicing
Code
PYTHON
Output
Adding Items
set.add(value)
adds the item to the set, if the item is not present already.Code
PYTHON
Output
Adding Multiple Items
set.update(sequence)
adds multiple items to the set, and duplicates are avoided.Code
PYTHON
Output
Removing Specific Item
set.discard(value)
takes a single value and removes if present.Code
PYTHON
Output
set_a.remove(value)
takes a value and remove if it present or raise an error.Code
PYTHON
Output
Operations on Sets
You can perform the following operations on Sets
- clear()
- len()
- Iterating
- Membership Check