Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use curly braces to initialize a Set in Python

I'm learning python, and I have a novice question about initializing sets. Through testing, I've discovered that a set can be initialized like so:

my_set = {'foo', 'bar', 'baz'}

Are there any disadvantages of doing it this way, as opposed to the standard way of:

my_set = set(['foo', 'bar', 'baz'])

or is it just a question of style?

like image 466
fvrghl Avatar asked Jun 28 '13 20:06

fvrghl


People also ask

What is the use of {} in Python?

In languages like C curly braces ( {} ) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.

How do you initialise a set in Python?

Initialize a SetYou can initialize an empty set by using set() . To intialize a set with values, you can pass in a list to set() .

Can you use curly braces in Python?

Easily my favorite advanced feature in Python, rather than relying on whitespace to denote scopes (boring) — we can use curly braces!

Which bracket are used to create a set in Python?

Sets are written with curly brackets ({}), being the elements separated by commas.


4 Answers

There are two obvious issues with the set literal syntax:

my_set = {'foo', 'bar', 'baz'}
  1. It's not available before Python 2.7

  2. There's no way to express an empty set using that syntax (using {} creates an empty dict)

Those may or may not be important to you.

The section of the docs outlining this syntax is here.

like image 164
bgporter Avatar answered Oct 14 '22 08:10

bgporter


Compare also the difference between {} and set() with a single word argument.

>>> a = set('aardvark')
>>> a
{'d', 'v', 'a', 'r', 'k'} 
>>> b = {'aardvark'}
>>> b
{'aardvark'}

but both a and b are sets of course.

like image 35
Thruston Avatar answered Oct 14 '22 07:10

Thruston


From Python 3 documentation (the same holds for python 2.7):

Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.

in python 2.7:

>>> my_set = {'foo', 'bar', 'baz', 'baz', 'foo'}
>>> my_set
set(['bar', 'foo', 'baz'])

Be aware that {} is also used for map/dict:

>>> m = {'a':2,3:'d'}
>>> m[3]
'd'
>>> m={}
>>> type(m)
<type 'dict'> 

One can also use comprehensive syntax to initialize sets:

>>> a = {x for x in """didn't know about {} and sets """ if x not in 'set' }
>>> a
set(['a', ' ', 'b', 'd', "'", 'i', 'k', 'o', 'n', 'u', 'w', '{', '}'])
like image 33
0x90 Avatar answered Oct 14 '22 07:10

0x90


You need to do empty_set = set() to initialize an empty set. {} is an empty dict.

like image 42
Arjjun Avatar answered Oct 14 '22 08:10

Arjjun