set() in Python

Question:

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.

Asked By: Michal Dostal

||

Answers:

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.

Answered By: FLAK-ZOSO

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!

Answered By: Jack Deeth

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

Answered By: geekay
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.