Getting The Length Of Set Python

Length Of Set Python

Now, we are going to learn about how we can get the length of the set. The length of the set means nothing but the number of elements/items in the set. In order to get the length of the set, we need to make use of the len function. Using the len function, we can also get the length of many other objects, like strings, lists, and tuples as well. So, Let’s have a look at a program, which tries to demonstrate the length of the set.

Length Of Set Python

As you can see, in the above program, we have created a set, using the set constructor, and we are trying to get the length of the set using the len function. You can also create a variable to store the length, but since we are more interested in the output now, we are directly going to print it. So, if you try executing the above program, you can simply have an output as 6, which is the length of the set. If you are confused that how can the length of the set be 6 if we are adding 7 elements to the set in the program? The answer to this is in the definition of the set. Basically, the set only allows unique values, and in the above list, 29 is a duplicate value, due to which, it is not added again, and the length of the set is 6.

So, at times, when we need to get the length of the set, we can make use of the len function. We need to pass on the reference variable to the len function, and it gives us the length of the set. So, as and when required, we can get the length of the set, using the len function.