[Python] Python subtleties

Bob Miller kbob at jogger-egg.com
Thu Sep 21 18:48:55 PDT 2006


Rob Hudson wrote:

> In Python, what's the difference between these two:
> 
> 1) var = ('val')
> 2) var = ('val',)

For any expression e, the expression (e,) means create a one-tuple
whose element is the value of e.

In statement 1, the parentheses are simply used to group, and the
string 'val' is assigned to var.  In statement 2, the magic rule I
just described is invoked, so var is assigned the tuple whose only
element is the string 'val'.

> Knowing that, is there a difference between these two?
> 
> 3) var = ('val1', 'val2')
> 4) var = ('val1', 'val2',)

They are the same.

The trailing comma in a tuple or arg list is ignored.  It makes it
easier for humans or programs to write in this format.

    var = (
           'val1',
           'val2',
           'val3',
           'val4',
           'val5',
	  )

The code below would produce the code above.  Code that left out the
last comma would be more involved.

    print 'var = ('
    for i in range(1, 6):
        print "           'val%d'," % i
    print '      )'

-- 
Bob Miller                              K<bob>
                                        kbob at jogger-egg.com


More information about the Python mailing list