How to add a string to set () if it does not break the string?

new_set = set('Hello')

I want just {'Hello'} instead of every single character as part of a set

+4
source share
4 answers

You can create a set and add elements to it later:

new_set = set()
new_set.add('Hello')
+4
source

Use a set of literals:

new_set = {'hello'}
+5
source

The set constructor expects iterability, and it adds each iterability item to the set. Rows are repeatable. Therefore, each letter of the string is added to the set.

Do this instead:

new_set = set(['Hello'])
+5
source

Several methods with timing (using python 2.7.8 on Windows 7):

letter:

my_set = {"Hello"}

Using timeit:

python -m timeit "s = {'Hello'}"
1000000 loops, best of 3: 0.0819 usec per loop

Empty set:

my_set = set()
my_set.add("Hello")

Using timeit:

python -m timeit "s = set()" "s.add('Hello')"
1000000 loops, best of 3: 0.222 usec per loop

Move the iteration as a set:

my_set = set(("Hello",)) # Equivalent to line below
my_set = set(["Hello"]) # Equivalent to line above

Using timeit:

python -m timeit "s = set(('Hello',))"
1000000 loops, best of 3: 0.237 usec per loop
0
source

All Articles