This difference is confusing me:
>>> s = "()())()"
>>> print set(s)
set([')', '('])
>>> print {s}
set(['()())()'])
Why?
From the Python documentation for the set()
method:
Return a new set object, optionally with elements taken from iterable.
Since a string is an iterable, the set()
method creates a set of all characters in the given string. However, since sets do not allow for duplicate values, the output is a set containing the two unique characters in the string: ')'
and '('
.
On the other hand, the shorthand syntax {s}
creates a set out of all items between the curly brackets. Since you only inserted one item s
(your string), the output was a set containing only that one item.
set()
takes an iterable as parameter, whose items will be the elements of the set.
So, set('my string') will contain each character of the iterable I passed it, that is {'m', 'y' ...}
Using {}
, you create the set by writing down each of its elements, separated by commas.
{'my string'} contains one element, the string 'my string'
When you write:
set(s)
it treats the string as an iterable, and makes a set containing its elements. The elements of a string are the individual characters. So it's equivalent to doing:
{'(', ')', '(', ')', ')', '(', ')'}
Since a set can't contain duplicate elements, you get a set with the two unique characters '('
and ')'
.
However, when you write:
{s}
it just makes a set whose element is the value of the variable. The {}
syntax treats each variable as a single element, rather than iterating over it.
The set()
function is frequently used to convert from one kind of collection to a set of its elements, that's why it iterates over it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With