I have used the set() function but I am confused.
x = set("car")
print(x)
Why does this code output: "a", "c", "r" and not "car"? Thanks for your answers.
I have used the set() function but I am confused.
x = set("car")
print(x)
Why does this code output: "a", "c", "r" and not "car"? Thanks for your answers.
The set()
function converts an iterable into a set. Because a string is an iterable collection of characters (well... of shorter, one-character strings), set("car")
becomes the set of its characters e.g. {"c", "r", "a"}
. (The order is random.)
There's three ways you can make a set containing the string "car":
my_string = "car"
my_set = {my_string}
my_string = "car"
temp_tuple = (my_string,)
my_set = set(temp_tuple)
my_string = "car"
my_set = set()
my_set.add(my_string)
If you just want a set containing specifically the word "car" you can construct this as a literal:
my_set = {"car"}
but I expect the actual problem you're trying to solve is more complex than that!
It's because of the main properties of set
in Python.
So things like this one just happen.
>>> set("car")
{'a', 'r', 'c'}
I suggest you to read this useful documentation about Python's set
.
If you really want an ordered set, there's something that can be useful to you.
I would suggest you to check this answers too.
if you just want one item in the set
do this
x = set(["car"])
print(x)
## or create a set directly like this
x=set({"car"})
set takes an iterable...a string is an iterable so it gets split if you pass a list even with one item..it will remain as such