Sets
Introduction to Python
Getting Started
Comments
Variables
Data Types
Type Casting
Input and Output
Operators
Strings
Booleans
Conditional Statements
While Loop
For Loop
Loop Control Statements
Lists
Tuples
Sets
Dictionaries
Functions
Function Arguments and Return Values
Variable Scope
Recursion
Lambda Functions
Arrays and Python Lists
Modules
Dates and Math
String Formatting
File Handling
Try and Except
Classes and Objects
Inheritance
Iterators
JSON
RegEx
Sets
Definition: A set is an unordered collection of items where every element is unique (no duplicates are allowed). Sets are written with curly brackets.
Why: Sets are included among the main collection types because they are highly efficient for operations where you need to ensure there are no duplicate entries (such as a list of unique visitor IDs) and for mathematical operations like unions and intersections.
Syntax
set_name = {item1, item2, item3}
Example
numbers = {1, 2, 3, 3, 4}
print(numbers)
Explanation
- Curly Brackets: Sets are defined using curly brackets
{ }. - Automatic Deduplication: Even though the number
3was added twice in the example, when Python prints the set, it will only display{1, 2, 3, 4}. Duplicate items are automatically removed.
Key Notes
- Sets are unordered, meaning the items do not have a defined order and can appear in a different order every time you print them. Because of this, you cannot access items by an index number (e.g.,
numbers[0]will cause an error). - Set items are unchangeable (immutable) once added, but you can add new items or remove existing ones using methods like
.add()and.remove().
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute