Syntactic sugar for assignment statements: one value to multiple targets?

Chris Angelico rosuav at gmail.com
Tue Aug 2 22:09:34 EDT 2011


On Wed, Aug 3, 2011 at 2:45 AM, gc <gc1223 at gmail.com> wrote:
> Anyway, I frequently need to initialize several variables to the same
> value, as I'm sure many do. Sometimes the value is a constant, often
> zero; sometimes it's more particular, such as defaultdict(list). I use
> dict() below.

If it's an immutable value (such as a constant integer), you can use
syntax similar to C's chained assignment:

a=b=c=0

If you do this with dict(), though, it'll assign the same dictionary
to each of them - not much use.

> # Option 3 (multiple target list: this seems the most Pythonic, and is
> normally what I use)
> # Concise, separates variables from assignments, but somewhat
> annoying; have to change individually and track numbers on both sides.
>
> a,b,c,d,e = dict(),dict(),dict(),dict(),dict()

I think this is probably the best option, although I would be inclined
to use dictionary-literal syntax:
a,b,c,d,e = {},{},{},{},{}

It might be possible to do something weird with map(), but I think
it'll end up cleaner to do it this way.

Chris Angelico



More information about the Python-list mailing list