Mutable default values for function parameters

Brian Quinlan BrianQ at
Thu Oct 4 20:58:27 CEST 2001

> I've used this idiom myself many times. I eventuallu decided
> it was shorter
> as
> def sample(x, d = None):
>     d = d or []
>     d.append(x)
>     print d
> but this looks so weird I'd appreciate confirmation that it's a
> replacement.

It is not a valid replacement because d can evaluate to zero for
values other than None e.g.

sample(x, '')
sample(x, 0)

Those should raise some sort of exception, not silently do the

You could change it to:
d = (d is None) or []

More information about the Python-list mailing list