Use curly braces to initialize a Set in Python

前端 未结 4 1092
别跟我提以往
别跟我提以往 2020-12-13 11:47

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          


        
相关标签:
4条回答
  • 2020-12-13 12:11

    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', '{', '}'])
    
    0 讨论(0)
  • 2020-12-13 12:20

    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.

    0 讨论(0)
  • 2020-12-13 12:29

    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.

    0 讨论(0)
  • 2020-12-13 12:30

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

    0 讨论(0)
提交回复
热议问题