Esther_T
Esther_T

Reputation: 71

What's the difference between '{}' and 'set()' in Python?

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

Upvotes: 5

Views: 5094

Answers (4)

Christian Weiss
Christian Weiss

Reputation: 151

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

Upvotes: 2

null
null

Reputation: 2137

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()

Upvotes: 6

szrg
szrg

Reputation: 89

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

Upvotes: -1

duckboycool
duckboycool

Reputation: 2455

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}.

Upvotes: 0

Related Questions