Lin Ma
Lin Ma

Reputation: 10139

confused by Python set initialization

Sometimes see code like below, and did some debugging, but still confused. Wondering whether it is initialized as a list of set()? A list of set(), and each element in a set is also a list? Post what I see in PyCharm and appreciate anyone could help to explain what the grammar mean, and how to read such line of code.

table = [set() for i in range(10)]

enter image description here

regards, Lin

Upvotes: 0

Views: 105

Answers (1)

TigerhawkT3
TigerhawkT3

Reputation: 49318

This is simply PyCharm's way of representing empty sets. The standard Python interpreter will instead use set(), as that is what you would enter into the interpreter to create an empty set and the consistency is helpful. Technically, set([]) sends an empty list to the set built-in function, which results in an empty set object, but you can get the same result with simply set(). I don't know why PyCharm's developers decided to represent an empty set in a different way.

In a standard Python interpreter:

>>> set()
set()
>>> set([])
set()

set([]) couldn't represent a set that contains an empty list, because list isn't a hashable type (and, as shown, that would be represented with {[]} anyway):

>>> {[]}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

If you want to know the reasoning behind this nonstandard representation, you'd have to ask PyCharm's developers.

Upvotes: 2

Related Questions