[Tutor] Tuple

Noufal Ibrahim noufal at nibrahim.net.in
Tue Apr 11 11:38:53 CEST 2006

On Tue, April 11, 2006 2:49 pm, Kaushal Shriyan wrote:
> Hi All
> I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap09.htm
>>>> tuple = ('a', 'b', 'c', 'd', 'e')
>>>> tuple[0]
> 'a'
> And the slice operator selects a range of elements.
>>>> tuple[1:3]
> ('b', 'c')
> But if we try to modify one of the elements of the tuple, we get a error:
>>>> tuple[0] = 'A'
> TypeError: object doesn't support item assignment
> Of course, even if we can't modify the elements of a tuple, we can
> replace it with a different tuple:
>>>> tuple = ('A',) + tuple[1:]
>>>> tuple
> ('A', 'b', 'c', 'd', 'e')
> How does tuple = ('A',) + tuple[1:]  this work ????

One question mark is enough. ;)

('A',) creates a tuple with a single element. The comma at the end is to
differentiate between a tuple and just grouping brackets.
tuple[1:] returns all elements of the tuple except the first.
So what do you have?
A tuple ('A') and another tuple ('b', 'c', 'd', 'e').

Now, the + operator concatenates these two into a new tuple. What do you get?

This is returned by the expression on the right hand side. And it's
assigned to the variable "tuple". When you print it, you get the value.

I think you're getting confused between changing a tuple itself and
creating a new one with pieces of others.

On a side note, it's not a good idea to call a variable "tuple" since
there is a python builtin by the same name.

More information about the Tutor mailing list