Tuesday, June 9, 2026
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

4 COMMENTS

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6895 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7018 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS