1

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...)?

KnightOfNi
  • 770
  • 2
  • 10
  • 17
  • 6
    *"as map() is encouraged in most cases over for x in y"* it's not – vaultah Jul 23 '14 at 20:09
  • @vaultah Isn't it? I could have sworn it was. There's even a question on it in here somewhere... https://stackoverflow.com/questions/1975250/when-should-i-use-a-map-instead-of-a-for-loop – KnightOfNi Jul 23 '14 at 20:11
  • @vaultah Ah, never mind. This answer here seems to tell us that the jury is still up... https://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map – KnightOfNi Jul 23 '14 at 20:19

3 Answers3

2

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.

Bartosz Marcinkowski
  • 6,651
  • 4
  • 39
  • 69
  • 2
    I would tend to agree with this answer, but for a different reason: those were originally functions meant to change the type of a variable (ie, you can apply `int()` or `list()` to a string). – KnightOfNi Jul 23 '14 at 20:14
2

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.

Community
  • 1
  • 1
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • wow, never knew about the `defaultdict()` bit. I wonder what happens if you use it on itself... – KnightOfNi Jul 23 '14 at 20:15
  • @KnightOfNi: It will become a two-dimensional defaultdict: `defaultdict(defaultdict)`. But if you try to lookup a non-existing key `d[missing][key]`, you'll end up with a KeyError. Assignments do work however, e.g. `d[new][key] = 1337`. BTW: Such an arbitrary builtin is officially called *default factory* – CodeManX Jul 23 '14 at 20:15
  • @KnightOfNi -- defaultdict can't be used on itself since the default_factory gets passed 0 arguments. You could do: `factory = lambda: defaultdict(factory)` and then `d = defaultdict(factory)` ;-) – mgilson Jul 23 '14 at 20:18
2

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.