2

What is the correct way to specify an empty dict or list for a function?

def func_a(l=list(), d=dict()):
    pass

def func_b(l=[], d={}):
    pass
BenDundee
  • 4,389
  • 3
  • 28
  • 34

2 Answers2

7

Either of those is fine if you're not going to mutate the input arguments...

However, if you're planning on mutating the list or the dict inside the function, you don't want to use either of the forms that you've supplied... You want to do something more like this:

def func(l=None, d=None):
    if l is None:
       l = list()  #or l = []
    if d is None:
       d = dict()  #or d = {}

Note that [] and {} will result in marginally faster execution. If this is in a really tight loop, I'd use that.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Thanks--hopefully this is one mistake I won't make again :) – BenDundee Jun 24 '13 at 19:11
  • 1
    I'm OT but I'd like to point out a link I saw yesterday about [] VS list() and {} VS dict(): http://stackoverflow.com/questions/2972212/creating-an-empty-list-in-python – Paolo Jun 24 '13 at 19:14
  • @Guandalino -- Thanks for the link. I don't really have a preference for either way to build the list/dict unless it's in a really tight loop where the extra function call might be noticeable. Generally that's not the case though. FWIW, in my code I think I generally use literals rather than empty function calls. – mgilson Jun 24 '13 at 19:19
3

Neither. Default arguments in Python are evaluated once, at function definition. The correct way is to use None and check for it in the function:

def func(l=None):
    if l is None:
        l = []
    ...

See the discussion in this SO question.

Community
  • 1
  • 1
andersschuller
  • 13,509
  • 2
  • 42
  • 33