Count the number of unique characters in a string in Python

In this tutorial, you will learn how to count the number of unique characters in a given string in Python.

Here, we are going to use some predefined functions to count the number of unique elements in a given string using python.

  •  set() is the predefined method used in this script.

1.set() method: set() method is unordered collection of unique elements of data.set() is used to eliminate  duplicates from the list or string. Although, we may get an unordered collection of data elements.

#Example on set()method
string='pavan'
s=set(string)
print('Elements:',s)

Output:

Elements:{'n','p','v','a'}
# Here, you can see that elements are not in order.

From the above code, the length of the set is equal to the number of unique elements in a given string. Since a set doesn’t allow duplicate values of elements.

to count the length of a set, we use a pre-defined method called len(). It returns the length of any object.
Let’s have a look at the following code: to count the number of elements:

string='pavan'
l=len(string) #Returns the Length of String
print('length:',l)
Output:
length:5

Since,the string “pavan” has 5 characters len()  returned an integer 5. Let’s have a glance over a small code below

Example: To count the number of unique elements:

string='codespeedy'
s=set(string)  #Creates a set of Unique Un-Ordered Elements
l=len(s)       #It returns the length of the above set.
print('Unique words:',l)

Output:

Unique words:7

Here, a set only allows you to store unique elements. Hence, the length of the set is equal to the number of unique elements in a given string.

Example: Without using set() function

Without using set(), we can use an alternative like a list or a string to find unique elements.
Here, the main constraint is :

  1. If the element in the string is not in the defined empty list (i.e. temp), we append that element to it and we can increase the number of unique values since it is the unique value in temp.
  2. If the same value is repeated we simply avoid it being appended to the list.
  3. Hence, our list (i.e. temp) consists of only unique values.

Let’s have a look at the following code:

string='codyspeedy'
count=0
temp=[]
for i in string:
    if(i not in temp):
        count+=1
        temp.append(i)
print('Total Unique Characters count:',count)    
        
        
        

Output:

Total Unique Characters count:7

So in this way, we can find the number of unique characters of a  given string.

For further reference Click Here ->Sets in Python

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *