[a,b,c,d] = 1,2,3,4

Tim Chase python.list at tim.thechases.com
Wed Aug 26 14:21:34 CEST 2015


On 2015-08-25 16:59, Jean-Michel Pichavant wrote:
> ----- Original Message -----
> > From: "Joel Goldstick" <joel.goldstick at gmail.com>
> > its called list unpacking or packing (?)
> > 
> > the right side is considered a tuple because of the commas
> > >>> a = 1,2,3
> > >>> a
> > (1, 2, 3)
> > >>> a[1]
> > 2
> 
> To add to Joel's answer, the right side can be *any* sequence, and
> is not restricted to lists or tuples.
> 
> a, b, c = (x for x in range(3)) # a generator for instance

Since range() *is* a generator, why not just use

    a, b, c = range(3)

I do this often for setting constants:

   (
   HR_FILE,
   PHONE_FILE,
   COST_CENTERS_FILE,
   ) = range(3)

however I have to keep track of how many entries are in there.  When
Py3 introduced variable tuple unpacking, I'd hoped the last one
wouldn't consume generators, allowing me to do something like

   (
   HR_FILE,
   PHONE_FILE,
   COST_CENTERS,
   *_
   ) = itertools.count()

so I could insert additional constants and have the list
automatically adjust.  Alas, no such joy.  The new Enum class does
offer an auto-number functionality, but it's clunky, IMHO.

https://docs.python.org/3/library/enum.html#autonumber 


-tkc





More information about the Python-list mailing list