0

My question is pretty short, is it bad python "style" to use l = list() rather than l = []? Or, similarly, d = dict() instead of d = {}?

Personally I find it more readable to write list(), dict(), set() etc. but I will avoid it if it is generally considered a "bad" way to write python code.

Var87
  • 427
  • 1
  • 3
  • 14
  • 1
    No problem. [A duplicate isn't a bad thing](https://stackoverflow.com/help/duplicates) :) – MSeifert Aug 24 '17 at 14:29
  • Juste check the dupe. `[]`, as well as `{}`, are faster than `list()` and `dict()`. Just don't ever make an optional argument default to `[]`. [Ever](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument). – Right leg Aug 24 '17 at 14:29
  • 1
    @Rightleg But `list()` as [default argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) is just as bad (and slower). – MSeifert Aug 24 '17 at 14:30
  • @MSeifert Yeah but it's more obvious that it's fishy, because there's a call, so it really feels weird... but, `def f(data=[])` feels very natural, or at least it felt natural to me. Sure, defaulting to `list()` is terrible anyway. – Right leg Aug 24 '17 at 14:33
  • I feel the dupe answers are slightly off compared to the question, why everything is about speed (no mention in either question)? To add to this, in terms of initialization, just go for what feels more readable but be aware that the two forms behave differently for non-empty initialization. – Gall Aug 24 '17 at 14:35
  • @Rightleg Why not ever? I occasionally use it when it's advantageous. – Stefan Pochmann Aug 24 '17 at 14:47
  • @StefanPochmann Well, if you can handle the side-effects it's alright, but to me it's just too complicated. On the other hand, `def f(data=None): if data is None: data = []` granted adds boilerplate, but is readable and short enough, besides keeping you safe from any counter-intuitive side effect. – Right leg Aug 24 '17 at 14:51
  • @Rightleg If with "side-effect" you mean that it's always the same object, then I'm using it **because of** that. – Stefan Pochmann Aug 24 '17 at 14:54
  • 1
    @StefanPochmann When specifically have you found it advantageous to use it? – Chris_Rands Aug 24 '17 at 14:57
  • @StefanPochmann I can imagine situations where this can be taken advantage of, but I still see it as a trick that harms readability. I'm not sure what it could accomplish that a class attribute or (sorry to say this but) a global variable couldn't... Well, anyway it's still valid Python, right? – Right leg Aug 24 '17 at 15:00
  • @Chris_Rands I think mostly in recursive functions, for memoization or for collecting results. – Stefan Pochmann Aug 24 '17 at 15:07

0 Answers0