0

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

asked Dec 3, 2015 at 7:45
12
  • 7
    It's a list of empty sets. Commented Dec 3, 2015 at 7:47
  • 1
    I don't know what PyCharm is up to, but table is just a list of ten empty sets. Commented Dec 3, 2015 at 7:49
  • 1
    If you're confused with the [] inside the sets, this indicates that the set is empty. Try set() in your Python shell. Commented Dec 3, 2015 at 7:50
  • 1
    I tried that and it just returns the repr() of an empty set: set(). Commented Dec 3, 2015 at 7:54
  • 1
    It is also exactly why I don't use anything more "helpful" than Notepad++. :P Commented Dec 3, 2015 at 7:57

1 Answer 1

2

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.

answered Dec 21, 2015 at 5:42
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.