Fix Python – Use curly braces to initialize a Set in Python


Asked By – fvrghl

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?

Now we will see solution for issue: Use curly braces to initialize a Set in Python


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.

This question is answered By – bgporter

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0