2

Possible Duplicate:
Why do we need tuples in Python (or any immutable data type)?

I'm learning Python and have background in Ruby. Not ever having tuples, I can't imagine why I would need them or why Python leans on them so much.

Community
  • 1
  • 1
Teffen Ellis
  • 113
  • 6
  • Not a duplicate. That asks "why immutable", whereas this asks about the fundamental nature and purpose of tuples themselves. – Ignacio Vazquez-Abrams Aug 10 '12 at 20:41
  • @IgnacioVazquez-Abrams: In what way doesn't it cover the same ground? Basically the only relevant difference is that tuples are immutable. Could any information go in an answer here that wouldn't go in the other question? – David Robinson Aug 10 '12 at 20:48
  • See [Understanding tuples vs. lists in Python](http://news.e-scribe.com/397) and [Python Tuples are Not Just Constant Lists](http://jtauber.com/blog/2006/04/15/python_tuples_are_not_just_constant_lists/). – Steven Rumbalski Aug 10 '12 at 20:50
  • If you take the time to learn the basics of some functional typed language (Haskell, Ocaml, ...) you'll see clearly the conceptual difference between arrays/lists and tuples. – tokland Aug 10 '12 at 21:38

3 Answers3

5

The coordinates of a square on a chessboard is one example of good use of tuple. I usually use a Python dict, indexed by tuple, to implement a multidimensional array, rather than list-of-lists or the numpy or array modules:

board = {}
board[ 3, 6 ] = "black queen"
board[ 0, 0 ] = "white king"

You can't use a mutable (like a list) as a dictionary key, so you need a tuple for this.

Occasionally you find yourself wanting to return multiple values from a function - a boolean to indicate success or failure plus a string describing the failure mode, for instance:

if trickyOperationSucceeds():
    return True,"Success!"
return False,"The tricky thing failed!"

This isn't a pattern to use a lot, but sometimes it gets you out of trouble. You could also use a list here; it's only by convention that you'd normally use tuple instead.

When considering how to represent independent values that have to be passed around together, there's almost a continuum between tuples, dicts, and classes. Consider three ways of representing that compound return:

(False, "The tricky thing failed!")
{ "status": False, "message": "The tricky thing failed!" }
ResultObject( status=False, message="The tricky thing failed!" )

If there's only one place in your code where you're doing this, the tuple is attractive for its terseness. If you're using this pattern a lot, and passing these result pairs back and forth between different modules, you might "upgrade" to the dict, where the elements have meaningful keys. If these results become a major part of your software design, you might upgrade them again to being instances of an object class. It's a balance between formality and ease of use.

Russell Borogove
  • 18,516
  • 4
  • 43
  • 50
3

A tuple is simply an immutable sequence, so you can't assign to the individual items of a tuple. One example might be a set of x-y coordinates like (5, 10), (-3, 20), (0, 0). If you needed to update some of these coordinates you could recreate the tuples like

coord = (5, 10)
# Our thing moves
newCoord = (coord[0] + dx, coord[1] + dy)
thegrinner
  • 11,546
  • 5
  • 41
  • 64
1

A tuple is supposed to be used for heterogenous data; it is the Python equivalent of C's struct or Pascal's record. Appending elements to such a type doesn't make sense, so there is no need for it to be mutable. Contrast with a list, which is for homogenous data:

people = [(u'Bob', 24), (u'Sally', 27)]
polygon = [(1, 1), (2, 3), (0, 0)]
David Robinson
  • 77,383
  • 16
  • 167
  • 187
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • Lists can absolutely have heterogeneous data. `["Bob", 22, (23, 9)]` works just fine. What's the difference? – David Robinson Aug 10 '12 at 20:47
  • @DavidRobinson: The difference is that iterating over *that* list requires you to treat each element differently, and therefore it is consequently slightly less Pythonic. – Ignacio Vazquez-Abrams Aug 10 '12 at 20:49
  • I still don't think it's an effective answer to the question. It's effectively saying that the difference is a matter of style, as opposed to the things you can do with an tuple (like hash it) that are actually impossible with a list. If I were new to Python, and I were told this was the only difference, it would seem unnecessary to me too. – David Robinson Aug 10 '12 at 20:51
  • 1
    @David: It is certainly not the *only* difference, but it is the among the **most important** of differences, as given by Guido back in 2003. – Ignacio Vazquez-Abrams Aug 10 '12 at 21:08
  • 1
    @DavidRobinson: Ignacio Vazquez-Abrams is on firm ground here. Here's a [direct quote](http://mail.python.org/pipermail/python-dev/2003-March/033964.html) from Guido van Rossum: "Tuples are for heterogeneous data, list are for homogeneous data. Tuples are *not* read-only lists." See also [Understanding tuples vs. lists in Python](http://news.e-scribe.com/397) and [Python Tuples are Not Just Constant Lists](http://jtauber.com/blog/2006/04/15/python_tuples_are_not_just_constant_lists/). They all make the same point. – Steven Rumbalski Aug 10 '12 at 21:09
  • That's a great point. Removed downvote (I had to make an insignificant edit to do so). – David Robinson Aug 10 '12 at 21:44