I tried x={}
but this gives a dict
I also tried x=set()
but when I do print(x) it gives output as set()
and not {}
How do I initialize and print a set such that if it is empty then it should show {} and not set()
Example: If the set has contents, then it gets printed as {1,2,3}
but if empty then I want it to show as {}
(and not as set()
). Does this need to be done programmatically using if len(x) = 0: then x='{}' else x ? Or is there any other approach to print an empty set as {} ?
set()
is correct. It is printed as set()
instead of {}
to distinguish it from a dict.
A short way to print a set as {}
if it is empty might be something like this:
x = set()
print(x or '{}')
Thus:
>>> x = set()
>>> print(x or '{}')
{}
>>> x.add(5)
>>> print(x or '{}')
{5}