Python Basics

Python Set

Alike list and tuple, there is another kind of data type exist in python and that is Set. Set is unordered and unindexed.

It means alike list and tuple, we can not access the elements of set using index number.

Example:

fruitnames={“Orange”,”Banana”,”Grape”}

How to access elements of Set?

By using for loop, we can print all the elements present in a set.

fruitnames={“Orange”,”Banana”,”Grape”}

for fruitname in fruitnames:

print(fruitname)

Output:

Orange

Banana

Grape

How to add elements in set?

To add elements in python set, we need to call add function of set.

Example:

fruitnames={“Orange”,”Banana”,”Grape”}

fruitnames.add(“Pine Apple”)

for fruitname in fruitnames:

print(fruitname)

Output:

Orange

Banana

Grape

Pine Apple

How to find number of total elements present in a tuple?

Alike list and tuple, we can use len function of python to calculate the total number of elements present in a set.

Example:

fruitnames={“Orange”,”Banana”,”Grape”}

print(fruitnames)

Output:

3