Sets
in Python are unordered collections of unique elements
.
They are used to store multiple items in a single variable and can be very useful for tasks involving membership testing, removing duplicates, and set operations like union, intersection, and difference
.
Properties of Sets
- Unordered - Sets do not maintain any order of elements. When you print a set, the items may appear in any order.
- Unique Elements - Sets automatically eliminate duplicate elements. Each element in a set must be unique.
- Mutable - You can add or remove items from a set.
- Iterable - You can iterate through the elements of a set using loops.
Creating Sets
You can create a set using curly braces {}
or the set()
function.
# Using curly braces my_set = {1, 2, 3, 4, 5} print(my_set) # Using the set() function another_set = set([1, 2, 3, 4, 5]) print(another_set)