3

When I use

a = {}

and

a = set()

And sometimes I see use like:

a = set([])

Are they the same? What's the difference between them?

I am asking because

a = set(range(5))
b = {0,1,2,3,4}
a == b
>>> True
Esther_T
  • 51
  • 3
  • Does this answer your question? [Creating an empty set](https://stackoverflow.com/questions/17663299/creating-an-empty-set) – user3840170 Feb 20 '22 at 17:21

4 Answers4

4

By default {} means an empty dictionary in python. However, the curly braces are used for both dict and set literals, see the following examples:

empty_set = set()
non_empty_set = {1,2,3}
empty_dict = {}
empty_dict2 = dict()
non_empty_dict = {"a": 1}

avoid using

a = set([]) # instead use a = set()
null
  • 1,944
  • 1
  • 14
  • 24
2

When you initialise the variable with empty brackets it will be of type dict:

a = {}
print(f"type of a={type(a)}")

Output:

type of a=<class 'dict'>

However, if you initialise it with some values python will detect the type itself.

b = {1, 2, 3}
print(f"type of b={type(b)}")

c = {"some_key": "some_value"}
print(f"type of c={type(c)}")

Output:

type of b=<class 'set'>
type of c=<class 'dict'>

A set and a dictionary are two different data structures. You can read more about them here: Beginner to python: Lists, Tuples, Dictionaries, Sets

Christian Weiss
  • 119
  • 1
  • 14
0

The literal {} will be a dictionary with key and value pairs, while set() is a set that contains just pure values. When using more than 0 elements, their literals will be distinguished by whether you include the key value pairs. For example, {1: 'a', 2: 'b'} vs {1, 2}.

duckboycool
  • 2,425
  • 2
  • 8
  • 23
-1

They are not the same.

{} creates and empty dictionary (but {1,2,3} creates a set with 3 elements: 1, 2, 3)

set() creates a empty set

szrg
  • 79
  • 5