Difference in formatting list and tuple values

Sean 'Shaleh' Perry shalehperry at attbi.com
Thu Dec 13 18:08:07 CET 2001


On 13-Dec-2001 Sue Giller wrote:
> I am trying to format values from either a list or a tuple, and I am 
> getting the following odd (to me) behavior.   I can format the tuple 
> entry using %d, but I get an error when I use the same formatting 
> for the same data in a list.
> Why does this happen?
> 
>>>> l = [1,2,3]                                                # list
>>>> t = (1,2,3)                                                # tuple
>>>> print "%02d" % t[:1]                       # format first entry in tuple ok
> 01
>>>> print "%02d" % l[:1]                       # get error with list
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> TypeError: an integer is required
>>>> print "%02d" % tuple(t[:1])                # cast to a tuple works ok
> 01
>

l[:1] returns [1], not 1.  The ':' is for slicing.  It returns a new list (or
tuple, or string) in the range specified.  If you just want the first item ask
for l[0].

Casting to a tuple works because the call then becomes:

"%02d" % (1,)

which is what the % operator expects -- a tuple of one item.




More information about the Python-list mailing list