Write A Python Program To Find Length Of Set

Given a set inside the Python program,  the program should find out the length of a set and then print it as  output.

There are two ways to print the length of a set,  keep reading…

 

 

Write A Python Program To Find Length Of Set



Write A Python Program To Find Length Of Set

Let's take a variable named my_set  and declare a few  integer data type variables inside it as shown below.

Now to get the length of the set use the built in function len()  and pass the set name as input argument.  This will  give us the length of the set.  use the print function call to bring the length of the set.

my_set = {1, 2, 3, 4, 5}

print("Length of Set is : ", len(my_set))




Second method
===================

There is another method to find the length of a set using a for loop,  initialize the index and it rate all the items present in the set using the for loop.  as we iterate all the items present in the for loop,  increment the index value.

 once the follow please completed,  index will store the length of set,  use the print function call to print the set length
 
my_set = {1, 2, 3, 4, 5}

index = 0
for item in my_set:
   index += 1

print("Length of Set is : ", index)




Output
=============
Length of Set is :  5



Python code 1
======================

my_set = {1, 2, 3, 4, 5}

print("Length of Set is : ", len(my_set))

 

 


Python code 2
=======================

my_set = {1, 2, 3, 4, 5}

index = 0
for item in my_set:
   index += 1

print("Length of Set is : ", index)



Output
================
Length of Set is :  5



Conclusion
=============
Execute the above mentioned Python program by modifying the values present in the set,  comment it down below if you have any suggestions to improve the above  Python program.





Post a Comment

0 Comments