Skip to content

Converting Strings to Sets - Removing Duplicates

CS 5001/5002 - Strings, Sequences & Sets

Code

#!/usr/bin/env python3
"""
Converting Strings to Sets - Removing Duplicates
CS 5001/5002 - Strings, Sequences & Sets

This file demonstrates:
- Converting strings to sets to find unique characters
- How sets automatically remove duplicates
- Order independence in sets vs sequences
"""

# A string with repeated characters
message = "hello world"
print(f"Original string: '{message}'")
print(f"Length: {len(message)}")

# Convert to set to see unique characters
unique_chars = set(message)
print(f"Unique characters: {unique_chars}")
print(f"Number of unique characters: {len(unique_chars)}")

# Convert back to sorted list to see the difference
sorted_unique = sorted(unique_chars)
print(f"Sorted unique characters: {sorted_unique}")

# Demonstrate that order is lost in sets
print(f"Set from 'abc': {set('abc')}")
print(f"Set from 'cba': {set('cba')}")  # Same set!

How to Use

  1. Copy the code above
  2. Save it as a .py file (e.g., strings_to_sets.py)
  3. Run it with: python strings_to_sets.py

Part of CS 5001/5002 - Strings, Sequences & Sets materials