List vs. Tuple

Skip Montanaro skip at mojam.com
Thu Oct 7 12:23:17 EDT 1999


    Matthew> Can someone explain to me why if there is only a string in a
    Matthew> list/tuple they behave differently when looped through.  For
    Matthew> example,

    >>>> list=['abcd']
    >>>> tuple=('abcd')

Matthew,

Your tuple isn't a tuple at all.  It's just a string.  To indicate a
singleton tuple you must include a trailing comma:

    tuple = ('abcd',)

This is an area of Python's syntax that often trips new users up (right
about when they get used to indentation-based block structure ;-).  Since
parens are used both to force expression evaluation order and to define
tuples, the trailing comma in the singleton tuple disambiguates the two
cases.  Lists don't have this problem since there is no ambiguity in the
semantic meaning of square brackets.

Now, stepping a bit away from the original problem...

You might find it helpful to get in the habit of always terminating tuples
and lists with a comma (though I must confess I only do this in one special
case myself).  This makes it less likely you'll get bitten by the bug that
bit you.  For large lists or tuples it can make it easier to insert new
entries.  For example, suppose you had a static list of first names:

    firsts = [ "Guido", "Jeremy", "Barry", "Mel" ]

Adding new names to the list gets to be a bother when your list gets big
enough cross a line boundary, so your natural instinct is to line wrap the
list:

    firsts = [ "Guido", "Jeremy", "Barry", "Mel", "Adam", "John", "Dana",
	       "Chevy", "Eddie", "Gilda", "Jane", "Kevin" ]

After a few more additions you might find it difficult to see what's been
added and want them alphabetized.  Once you cross this threshold, it's
easier to just make them one string per line and terminate each string with
a comma.  You can then use an external sort program with impunity to sort
the list after adding new names:

    firsts = [
	       "Adam",
	       "Barry",
	       "Chevy",
	       "Dana",
	       "Eddie",
	       "Fred",
	       "Gilda",
	       "Guido",
	       "Jane",
	       "Jeremy",
	       "John",
	       "Kevin",
	       "Mel",
	      ]

Now, this is not a generally going to be a good way to maintain long static
lists or tuples, but for the occasional case it works, and the trailing
comma thing makes it easier to sort the items without worrying about where
you need to insert or delete commas.

Far enough afield for you?

Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/
847-971-7098   | Python: Programming the way Guido indented...




More information about the Python-list mailing list