x, = y (???)

Terry Reedy tjreedy at udel.edu
Thu Jul 17 17:32:30 EDT 2008



kj wrote:
> 
> 
> I just came across an assignment of the form
> 
>   x, = y
> 
> where y is a string (in case it matters).
> 
> 1. What's the meaning of the comma in the LHS of the assignment?
> 2. How could I have found this out on my own?

1.Experiment with the interactive interpreter.  It is sooo easy.

 >>> x, = '1'
 >>> x
'1'
 >>> x, = '12'
Traceback (most recent call last):
   File "<pyshell#53>", line 1, in <module>
     x, = '12'
ValueError: too many values to unpack
 >>> x,y = '12'
 >>> x,y
('1', '2')
 >>> x, = 3
Traceback (most recent call last):
   File "<pyshell#45>", line 1, in <module>
     x, = 3
TypeError: 'int' object is not iterable
 >>> *x, = [3]
 >>> x
[3]

2. Read the Python docs which come with the interpreter.
LanguageReference/SimpleStatements/AssignmentStatements:
"If the target list is a comma-separated list of targets:
...
Else: The object must be a sequence with the same number of items as 
there are targets in the target list, and the items are assigned, from 
left to right, to the corresponding targets."
which is exactly the behavior observed above.




More information about the Python-list mailing list