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 
1
  • 1
    Off-topic: You should not use mutable values as default argument value. Commented Jun 24, 2013 at 19:07

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks--hopefully this is one mistake I won't make again :)
I'm OT but I'd like to point out a link I saw yesterday about [] VS list() and {} VS dict(): stackoverflow.com/questions/2972212/…
@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.
I'm curious how this works with type annotations. We can't do def func(foo: set(str) = None): if foo is None: ... Because this produces an error in type checkers.
You typically do def func(foo: set[str] | None = None) -> ...:
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.