Day31-Sets

Python Sets
Sets are unordered collection of data items. They store multiple items in a single variable. Set items are separated by commas and enclosed within curly brackets {}. Sets are unchangeable, meaning you cannot change items of the set once created. Sets do not contain duplicate items.
Example:
info = {"Carla", 19, False, 5.9, 19}
print(info)
Output:
{False, 19, 5.9, 'Carla'}
Here we see that the items of set occur in random order and hence they cannot be accessed using index numbers. Also sets do not allow duplicate values.
Quick Quiz: Try to create an empty set. Check using the type() function whether the type of your variable is a set
Accessing set items:
Using a For loop
You can access items of set using a for loop.
Example:
info = {"Carla", 19, False, 5.9}
for item in info:
print(item)
Output:
False
Carla
19
5.9
Practice
s = {2, 4, 2, 6}
print(s)
info = {"Carla", 19, False, 5.9, 19}
print(info)
harry = set()
print(type(harry))
for value in info:
print(value)
Output:
{2, 4, 6}
{False, 19, 5.9, 'Carla'}
<class 'set'>
False
19
5.9
Carla
Explanation
s = {2, 4, 2, 6}Creates a set named
s.Duplicate values are automatically removed because sets store only unique elements.
print(s)- Displays the contents of the set.
info = {"Carla", 19, False, 5.9, 19}Creates a set containing different data types.
Duplicate values are removed automatically.
print(info)- Displays all elements of the set.
harry = set()Creates an empty set.
set()is used because{}creates an empty dictionary.
print(type(harry))- Shows the data type of the variable
harry.
- Shows the data type of the variable
for value in info:- Iterates through each element in the set
info.
- Iterates through each element in the set
print(value)- Prints each element one by one during the loop.
Key Points
Sets store only unique values.
Duplicate elements are automatically removed.
Sets are unordered collections.
Sets can contain elements of different data types.
Use
set()to create an empty set.



