-1

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.

FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28

3 Answers3

3

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":

  1. Make the set directly using braces:
my_string = "car"
my_set = {my_string}
  1. Put the string into another iterable and convert that
my_string = "car"
temp_tuple = (my_string,)
my_set = set(temp_tuple)
  1. Make an empty set and add the string to it
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!

Jack Deeth
  • 3,062
  • 3
  • 24
  • 39
0

It's because of the main properties of set in Python.

  • They can't contain duplicates
  • They're unordered

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.

FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28
  • Thank you. And one more question. When do we use set("ford") and when car = {"ford", "honda"} – Michal Dostal Feb 05 '23 at 10:42
  • Well, if you want a set[str] you use the second one, while the first one will return a set of characters taken from the "ford" str. They will both be a set[str] since Python has no "char" type, but the first one will be like an unordered {"f", "o", "r", "d"}. If the answer was helpful please accpet it to mark it as a working one. – FLAK-ZOSO Feb 05 '23 at 10:43
-1

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

geekay
  • 340
  • 1
  • 5