'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
Solution 1:[1]
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()
Solution 2:[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
Solution 3:[3]
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}.
Solution 4:[4]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | null |
| Solution 2 | Christian Weiss |
| Solution 3 | duckboycool |
| Solution 4 | szrg |
