length of a tuple or a list containing only one element

Ben Finney bignose+hates-spam at benfinney.id.au
Mon Nov 3 07:30:04 EST 2008


TP <Tribulations at Paralleles.invalid> writes:

> Hi everybody,
> 
> I have a question about the difference of behavior of "len" when
> applied on tuples or on lists. I mean:
> 
> $ len( ( 'foo', 'bar' ) )
> 2
> $ len( ( 'foo' ) )
> 3
> $ len( [ 'foo', 'bar' ] )
> 2
> $ len( [ 'foo' ] )
> 1

For making a literal tuple, parentheses are irrelevant; only the
commas matter:

    >>> type( ('foo', 'bar') )
    <type 'tuple'>
    >>> type( ('foo',) )
    <type 'tuple'>
    >>> type( ('foo') )
    <type 'str'>

However, for making a literal list, the brackets do matter:

    >>> type( ['foo', 'bar'] )
    <type 'list'>
    >>> type( ['foo',] )
    <type 'list'>
    >>> type( ['foo'] )
    <type 'list'>

-- 
 \      “The way to build large Python applications is to componentize |
  `\             and loosely-couple the hell out of everything.” —Aahz |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list