[Tutor] Tuple

Alan Gauld alan.gauld at freenet.co.uk
Tue Apr 11 13:36:29 CEST 2006


>>> tuple = ('A',) + tuple[1:]
>>> tuple
>('A', 'b', 'c', 'd', 'e')
>
> How does tuple = ('A',) + tuple[1:]  this work ????
>
> Please explain me with an example

OK, we will use the example you gave us!

tuple is a bad name since Python has an internal type 
called tuple usd for converting a list etc to a tuple so 
I'll use t1:

>>> t1 = ('a','b','c','d','e')
>>> t2 = ('A',) + t1[1:]

We construct a new tuple by creating a single element 
tuple ('A',) and adding to it the contents of the original 
tuple starting with the second element (t1[1:]). We can 
add tuples together quite easily:

>>> t3 = (1,2,3) + (4,5,6)
>>> t3
(1,2,3,4,5,6)

The result is a new tuple. The only difference in your 
example is that instead of using a new name (t2) you 
replaced the original tuple with the new one in t1. This 
is just the same as when you do

x = x +1

Now which specific bit of that did you not understand
and we can expand on it if necessary?

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list