TUPLE & LIST

Christos TZOTZIOY Georgiou tzot at sil-tec.gr
Thu Jan 15 15:54:32 CET 2004


On Thu, 15 Jan 2004 15:08:42 +0100, in comp.lang.python you wrote:

>HI,
>
>1) what are the differences between list and tuple?

A list is a mutable (ie updatable) container for objects; you can add or
remove objects as much as you like.  A tuple is an immutable (ie not
updatable) container, which, once created, cannot change.

The general idea is that a tuple is something like a record in Pascal or
a struct in C (without any named members), so the order of its contents
is important.  For example, the function localtime of the time module
returns a tuple, whose first member is the year, second member is the
month etc.
OTOH, the order of some list's contents should bear no special meaning;
therefore a list has methods as .sort(), .reverse() etc.

Examples:
Use a list for a list of names.
Use a tuple for (x,y) coordinates in some area.
Use a list of (name,phone,address) tuples for your poor man's address
book which you will implement in python.

>2) how to concatenate tuple and list? no method, no op?tor?

Convert either one to the type of the other.

If the final result should be a tuple, do something like:

final_tuple= your_tuple + tuple(your_list)

But you probably want a list, so do something like:

final_list= list(your_tuple) + your_list

>3) im looking the fucking manual, and cant add value in my tuple, when it
>already created :/

That's the whole idea, like the FM says in
http://www.python.org/doc/current/ref/types.html .  A tuple cannot be
changed, therefore it consumes less space than a list and can be used as
a key, say, in a dictionary (unlike a list).

>  how to do it?

# You can't, but tuples can be concatenated:

>>> a = 1,2,3
>>> b = 4,5,6
>>> print a
(1, 2, 3)
>>> print b
(4, 5, 6)
>>> print a+b
(1, 2, 3, 4, 5, 6)

# or sliced:

>>> print a[:2]+b[2:]
(1, 2, 6)

# or indexed

>>> print "the first member of %s is %s" % (a, a[0])

HTH
-- 
TZOTZIOY, I speak England very best,
Ils sont fous ces Redmontains! --Harddix



More information about the Python-list mailing list