[Tutor] Why use tuples?
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Thu, 20 Sep 2001 14:55:20 -0700 (PDT)
On Thu, 20 Sep 2001, Danny Kohn wrote:
> What I understand about the difference in functionality between lists
> and tuples is that tuples are restricted lists.
It's a little safer to say that tuples and lists are both "sequences",
things that have elements that we're able to pull out. Strings are also
sequences, so all of these work:
###
>>> for x in (1, 2, 3): print x
...
1
2
3
>>> for x in [1, 2, 3]: print x
...
1
2
3
>>> for x in "123": print x
...
1
2
3
###
Tuples conceptually do a similar thing with lists: they are containers
that hold values.
> But what why would I want to use tuples? What is the benefit?
Good question. Python actually does quite a bunch of tuple stuff behind
our backs. For example, when we do something like this:
###
>>> x, y = 1, 2
>>> x
1
>>> y
2
###
... that's all tuples in the background doing the work. What's happening
above is called "tuple assignment" because Python first constructs the
tuple (1, 2), and then pairwise assigns each value to its corresponding
variable.
Python also uses tuples whenever we want to return multiple values from a
function:
###
>>> def quadraticSolver(a, b, c):
... """This is a function that solves the quadradic equation,
... ax**2 + bx + c = 0"""
... discriminant = math.sqrt(b**2 - 4 * a * c)
... return (-b + discriminant)/(2*a), (-b - discriminant)/(2*a)
>>> quadraticSolver(5, 2, -3)
(0.59999999999999998, -1.0)
###
So tuples can be used by Python to quickly stuff multiple things into a
"single" container.
It's true that lists have more capabilities than tuples, but there's
something of an additional cost to them: they're more complicated because
they can do so much. Lists have... let's see...
###
>>> dir([])
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']
###
... quite a few methods we can play with. Tuples don't, but sometimes
simplicity is a good thing.
Compared to lists, tuples are very "lightweight": they support the very
minimum that a "sequence" should do, and because of that, they're
computationally cheaper to work with. Tuples also correspond nicely with
the mathematical concept by the same name, so if you're a mathematician,
you'll feel right at home. *grin*
But it's not necessarily a terrible thing if we get a tuple and want it as
a list: it's actually easy to go from tuples to lists and vice versa
because Python gives us a bunch of type-converting functions:
###
>>> secret_message = "hello world"
>>> list(secret_message)
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> tuple(secret_message)
('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')
>>> list(tuple(list(secret_message)))
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> ''.join(list(tuple(list(secret_message))))
'hello world'
###
If you have more questions, please feel free to ask.