CONTENT
1. Introduction
2 Sets Methods
​Introduction
A Python set is an unordered collection of unique elements. This is crucial! 'Unordered' means the elements don't have a specific position or index like lists. 'Unique' means no duplicate values are allowed."
"Think of it like a mathematical set. You can have a set of numbers, a set of names, but you can't have the same element appear twice."
Properties:
- Unordered – The elements do not have a fixed position.
- Unique – Duplicate values are not allowed.
- Mutable – You can add and remove elements.
- Supports Set Operations – Union, Intersection, Difference, etc.
CREATING SETS
Creating sets using either curly braces { } or set constructor set( )
1. Using { } curly brackets:
Syntax: {elements}
​Code </>:
​# Creating set using curly braces {}​
my_set = {1, 2, 3, 4, 5}
print(my_set)
Output:
{1, 2, 3, 4, 5}
2. Using set() constructor:
Syntax: set(elements)
​Code </>:
​# Creating set using set constructor set()
my_set = set([1, 2, 3, 4, 5]
print(my_set)
Output:
{1, 2, 3, 4, 5}
SETS METHODS
​Sets Methods
In Python, tuples are immutable sequences, meaning once they are created, their contents cannot be changed. Because of this immutability, tuples have fewer built-in methods compared to mutable data types like lists.
If you need to modify a tuple, you can convert it to a list, make changes, and then convert it back to a tuple.
1. count(item): Returns the number of times a specified value appears in the tuple.
Syntax: tuple.count(value)
value: The value to search for.
​Code </>:
​# count number of occurrence of 2​
my_tuple = (1, 2, 3, 2, 4, 2)
print(my_tuple.count(2))
Output:
3
2. index(value, start, end): Returns the index of the first occurrence of a specified value in the tuple.
​Syntax: tuple.index(value, start, end)
value: The value to search for.
start (optional): The index to start the search from.
end (optional): The index to end the search at.
​Code </>:
​# search index of first occurrence of element 2 from beginning
my_tuple = (1, 2, 3, 2, 4, 2)
print(my_tuple.index(2))
Output:
1
​Code </>:
​​# search index of first occurrence of element 2 after index 2 but before 5 (excluding)
my_tuple = (1, 2, 3, 2, 4, 2)
print(my_tuple.index(2, 2, 5))
Output:
3
