Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Count the Number of matching characters in a pair of strings
Next article icon

Count the number of Unique Characters in a String in Python

Last Updated : 20 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a string, and our task is to find the number of unique characters in it. For example, if the string is “hello world”, the unique characters are {h, e, l, o, w, r, d}, so the output should be 8.

Using set

Set in Python is an unordered collection of unique elements automatically removing duplicates when created from a string. The number of unique characters in string can be determined by finding length of set using len().

Python
a = "hello world"  # Convert the string to a set u_ch = set(a)  # Count the number of unique characters u_c = len(u_ch)  print(f"Number of unique characters: {u_c}") 

Output
Number of unique characters: 8 

Explanation:

  • Code converts the string “hello world” to a set (set(a)) to extract unique characters as sets automatically remove duplicates.
  • It calculates number of unique characters using len(u_ch) and displays count using a formatted string.

Using collections.Counter

collections.Counter counts character frequencies in a string and stores them as key-value pairs. The number of unique characters is length of Counter object representing distinct keys.

Python
from collections import Counter  a = "hello world" ch = Counter(a) u_c = len(ch)  print(f"Number of unique characters: {u_c}") 

Output
Number of unique characters: 8 

Explanation:

  • Counter(a) counts the frequency of each character in string “hello world” and stores counts in a dictionary-like structure.
  • Number of unique characters is determined using len(ch) which gives total number of distinct keys (characters) in Counter.

Using a manual loop

A manual loop iterates through each character in string and adds it to a list or set if it is not already present ensuring only unique characters are tracked. The number of unique characters is then determined by counting the length of resulting collection.

Python
s = "hello world" u_ch = [] for char in s:     # If the character is not already in the list, add it     if char not in u_ch:         u_ch.append(char)  # Calculate the number of unique characters  u_c = len(u_ch) print(f"Number of unique characters: {u_c}") 

Output
Number of unique characters: 8 

Explanation:

  • Loop iterates through each character in the string and appends it to the u_ch list only if it hasn’t been added before ensuring all characters are unique.
  • Length of u_ch list is calculated using len() representing number of unique characters in string.


Next Article
Count the Number of matching characters in a pair of strings

T

thotasravya28
Improve
Article Tags :
  • DSA
  • Hash
  • Python
  • Python-Quizzes
  • Strings
  • Technical Scripter
  • HashSet
  • python-set
Practice Tags :
  • Hash
  • python
  • python-set
  • Strings

Similar Reads

  • Count the number of unique characters in a given String
    Given a string, str consisting of lowercase English alphabets, the task is to find the number of unique characters present in the string. Examples: Input: str = “geeksforgeeks”Output: 7Explanation: The given string “geeksforgeeks” contains 7 unique characters {‘g’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’}. Inp
    14 min read
  • Python | Count the Number of matching characters in a pair of string
    The problem is about finding how many characters are the same in two strings. We compare the strings and count the common characters between them. In this article, we'll look at different ways to solve this problem. Using Set Sets are collections of unique items, so by converting both strings into s
    2 min read
  • Count the Number of matching characters in a pair of strings
    Given a pair of non-empty strings str1 and str2, the task is to count the number of matching characters in these strings. Consider the single count for the character which have duplicates in the strings.Examples: Input: str1 = "abcdef", str2 = "defghia" Output: 4 Matching characters are: a, d, e, fI
    7 min read
  • Count occurrences of a character in string in Python
    We are given a string, and our task is to count how many times a specific character appears in it using Python. This can be done using methods like .count(), loops, or collections.Counter. For example, in the string "banana", using "banana".count('a') will return 3 since the letter 'a' appears three
    2 min read
  • Python program to check if a string contains all unique characters
    To implement an algorithm to determine if a string contains all unique characters. Examples: Input : s = "abcd" Output: True "abcd" doesn't contain any duplicates. Hence the output is True. Input : s = "abbd" Output: False "abbd" contains duplicates. Hence the output is False. One solution is to cre
    3 min read
  • Count the number of times a letter appears in a text file in Python
    In this article, we will be learning different approaches to count the number of times a letter appears in a text file in Python. Below is the content of the text file gfg.txt that we are going to use in the below programs: Now we will discuss various approaches to get the frequency of a letter in a
    3 min read
  • Count of all unique substrings with non-repeating characters
    Given a string str consisting of lowercase characters, the task is to find the total number of unique substrings with non-repeating characters. Examples: Input: str = "abba" Output: 4 Explanation: There are 4 unique substrings. They are: "a", "ab", "b", "ba". Input: str = "acbacbacaa" Output: 10 App
    6 min read
  • Find all duplicate characters in string in Python
    In this article, we will explore various methods to find all duplicate characters in string. The simplest approach is by using a loop with dictionary. Using Loop with DictionaryWe can use a for loop to find duplicate characters efficiently. First we count the occurrences of each character by iterati
    3 min read
  • Count number of substrings of a string consisting of same characters
    Given a string. The task is to find out the number of substrings consisting of the same characters. Examples: Input: abba Output: 5 The desired substrings are {a}, {b}, {b}, {a}, {bb} Input: bbbcbb Output: 10 Approach: It is known for a string of length n, there are a total of n*(n+1)/2 number of su
    6 min read
  • String with maximum number of unique characters
    Given an array of strings, the task is to print the string with the maximum number of unique characters. Note: Strings consists of lowercase characters.If multiple strings exists, then print any one of them.Examples: Input: arr[] = ["abc", "geeksforgeeks", "gfg", "code"]Output: "geeksforgeeks" Expla
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences