[Tutor] comma in an assignment

Steven D'Aprano steve at pearwood.info
Wed Oct 23 03:50:01 CEST 2013


On Tue, Oct 22, 2013 at 07:20:25PM +0000, Key, Gregory E (E S SF RNA FSF 1 C) wrote:

> I understand that a comma in Python is a separator and not an 
> operator. In some of the MatPlotLib examples I see code like this:
> 
> line1, = ax1.plot(t, y1, lw=2, color='red', label='1 HZ')
> 
> What does the comma do in an assignment statement?

It does "sequence unpacking".

On the right hand side, commas create a tuple:

py> x = 100, 200, 300
py> print(x, type(x))
(100, 200, 300) <class 'tuple'>


On the left hand side, you can think of it as if it creates a tuple of 
names, then assigns to each name with the corresponding item from the 
other side:

py> a, b, c = 100, 200, 300
py> print(a, b, c)
100 200 300

So this example is conceptually like:

# make a tuple of names
(a, b, c)
# line them up with a sequence on the right hand side
(a, b, c) = (100, 200, 300)
# unpack the sequence on the right and assign item-by-item
a <-- item 0 = 100
b <-- item 1 = 200
c <-- item 2 = 300


So a single comma on the left, like this:

    a, = function(args, more_args)

is equivalent to this:

    temp <-- function(args, more_args)
    a    <-- temp[0]
    delete temp

except of course the name "temp" isn't literally used.

The values on the right don't have to be a tuple, any sequence will do, 
such as strings, lists, or iterators:

py> a, b, c = "XYZ"
py> print(a, b, c)
X Y Z

However, there does have to be the same number of items on both sides:

py> a, b, c = "xy"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack


-- 
Steven


More information about the Tutor mailing list