Friday, September 26, 2025
HomeLanguagesConvert String to Set in Python

Convert String to Set in Python

We can convert a string to setin Python using the set() function.

Syntax : set(iterable) Parameters : Any iterable sequence like list, tuple or dictionary. Returns : An empty set if no element is passed. Non-repeating element iterable modified as passed as argument.

Example 1 : 

python




# create a string str
string = "Lazyroar"
print("Initially")
print("The datatype of string : " + str(type(string)))
print("Contents of string : " + string)
 
# convert String to Set
string = set(string)
print("\nAfter the conversion")
print("The datatype of string : " + str(type(string)))
print("Contents of string : ", string)


Output : 

Initially
The datatype of string : 
Contents of string : Lazyroar

After the conversion
The datatype of string : 
Contents of string :  {'k', 's', 'g', 'e'}

Example 2 : 

python




# create a string str
string = "Hello World!"
print("Initially")
print("The datatype of string : " + str(type(string)))
print("Contents of string : " + string)
 
# convert String to Set
string = set(string)
print("\nAfter the conversion")
print("The datatype of string : " + str(type(string)))
print("Contents of string : ", string)


Output : 

Initially
The datatype of string : 
Contents of string : Hello World!

After the conversion
The datatype of string : 
Contents of string :  {'r', 'H', ' ', 'l', 'o', '!', 'd', 'W', 'e'}

Method: Using set brackets and start operator. 

Algorithm: 

  • Initialize test string. 
  • Use the start operator to string traverse the string character by character and uses set brackets to hold them 
  • Print result. 

Python3




# create a string str
string = "Lazyroar"
print("Initially")
print("The datatype of string : " + str(type(string)))
print("Contents of string : " + string)
 
# convert String to Set
string = {*string}
print("\nAfter the conversion")
print("The datatype of string : " + str(type(string)))
print("Contents of string : ", string)


Output

Initially
The datatype of string : <class 'str'>
Contents of string : Lazyroar

After the conversion
The datatype of string : <class 'set'>
Contents of string :  {'s', 'k', 'e', 'g'}

Time complexity: O(N) Where N is the length of a string. 

Auxiliary space: O(M) Where M is the length of a new set. 

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32320 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6683 POSTS0 COMMENTS
Nicole Veronica
11854 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11910 POSTS0 COMMENTS
Shaida Kate Naidoo
6795 POSTS0 COMMENTS
Ted Musemwa
7071 POSTS0 COMMENTS
Thapelo Manthata
6756 POSTS0 COMMENTS
Umr Jansen
6762 POSTS0 COMMENTS