Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

differences for creating set using set() or {}

Tags:

python

This difference is confusing me:

>>> s = "()())()"
>>> print set(s)

set([')', '('])

>>> print {s}

set(['()())()'])

Why?

like image 957
Gene Xu Avatar asked Dec 24 '18 23:12

Gene Xu


3 Answers

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.

like image 168
yuvgin Avatar answered Oct 19 '22 11:10

yuvgin


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'

like image 6
Thierry Lathuille Avatar answered Oct 19 '22 11:10

Thierry Lathuille


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.

like image 6
Barmar Avatar answered Oct 19 '22 11:10

Barmar