Reputation: 850
As most Python users know, there are two ways of creating x as an empty string or list (or, for integers, 0). You could do:
x = str()
y = list()
z = int()
or, you could do:
x = ""
y = []
z = 0
I know that these are semantically identical statements, but is one more encouraged than the other (as map()
is encouraged in some cases over for x in y...
)?
Upvotes: 1
Views: 307
Reputation: 309881
I like to live by the mantra "say what you mean". If you want an empty string, use ""
. If you want 0
, use 0
.
The function form is useful for getting an empty value of an arbitrary builtin:
d = defaultdict(list)
As a side benefit, when you use literals it is also marginally faster since python doesn't need to look up int
, str
, list
which could be shadowed.
It is worth pointing out that there are famous pythonistas who would disagree with me.
Upvotes: 2
Reputation:
str([object])
returns a printable representation of an object.
list([iterable])
returns a list based off of iterable
int([object])
converts a string or number to integer.
Each of these functions return a default value if no parameter is passed. I'm not sure why you'd use these functions instead of ""
, []
and 0
.
Upvotes: 2
Reputation: 6861
I think it is more common and more pythonic to do
x = ""
y = []
z = 0
It is more explicit, because you don't expect the reader to know what is the default value for a type.
Upvotes: 2