2

recently I was reviewing my python notebook, and here comes my problem wish to share with talents here:

As far as I know, if you creating an empty set : you can only use set() because {} will return an empty dictionary.

else: you can use both set()and{}to create a nonempty set.

For example:

a = {1,2,3,3,3,3}
a

it returns {1,2,3}

or set(X) something but it only takes one argument X

a = [1,2,3,3,3,3]
set(a)

it returns {1, 2, 3}.

But we cannot apply a list in {}

a = {[1,2,3,3,3,3]}

TypeError: unhashable type: 'list'

My question is:
1. why {}do not accept the list?
2. apart from creating an empty set, what are other differences between set() and {}.

If you can give some small examples to demonstrate the difference that would be great.

Thank you

Shan Jiang
  • 43
  • 5
  • 2
    Because you're passing an unhashable object as a *single element* in a set, if you wanted to unpack the list to separate elements that would be `{*[...]}` – jonrsharpe Jun 02 '20 at 06:44
  • `print(type({1}))` this is a set. A dictionary is based on key-value pairs. A set is an unordered list with no duplicates. – Tin Nguyen Jun 02 '20 at 06:46
  • 2
    Basically `set()` is a function that has special handling for iterator arguments. `{}` on the other hand is used for `dict` and `set` literals. A similar analogy would be to use `"1"` vs `str(1)` to create strings. – Selcuk Jun 02 '20 at 06:48

0 Answers0