Lists and Tuples and Much More

7stud bbxx789_05ss at yahoo.com
Thu Apr 12 19:10:37 EDT 2007


> Now I read somewhere that you could change the
> list inside that tupple.  But I can't find any
> documentation that describes HOW to do it.

t = (1, 2, ["red", "white"])
t[2][1] = "purple"
print t

t[2] returns the list, so the second line is equivalent to:

lst = t[2]
lst[1] = "purple"

That is exactly how you would access and change a list inside a list,
e.g.:

[1, 2, ["red", "white"]]

> And which is better on resources....I'm guessing a tuple seeing
> as it doesn't change.

I doubt it matters much unless you have several million lists v.
several million tuples.  The reason you need to know about tuples is
because they are returned by some built in functions.  Also, a key in
a dictionary can be a tuple, but not a list.  But using a tuple as a
key in a dictionary is probably something you will never do.


> Now there comes append.  I read everywhere that append only add's 1
> element to the end of your list.  But if you write:

>>> my_list = [1, 2, 3, 4, 5, 6]
>>> my_list.append([7, 8, 9, 10])
>>> my_list _li

[1, 2, 3, 4, 5, 6, [7, 8, 9, 10]]

> Is that because list's, no matter what they contain, are counted as
> 1 element?

Each "element" in a list is associated with an index position.  When
you append() to a list you are creating one additional index position
in the list and assigning the thing you append to that index
position.  The thing you append becomes one element in the list, i.e.
it's associated with one index position in the list.  As a result,
when you append(), the length of the list only increases by 1:

>>> l = [1, 2]
>>> len(l)
2
>>> a = ["red", "white"]
>>> l.append(a)
>>> l
[1, 2, ['red', 'white']]
>>> len(l)
3
>>>



> And how would you sort the list that's in the list?

By summoning up the list, and then sorting it:

t = (1, 2, ["red", "white", "ZZZ", "abc"])
t[2].sort()
print t




More information about the Python-list mailing list