[Tutor] creating a list of data . . .
Scott Widney
SWidney at ci.las-vegas.nv.us
Tue Aug 26 09:45:34 EDT 2003
> Concatenation is perfectly legal:
>
> >>> tuple = (1, 2, 3, 4)
> >>> tuple = tuple + (5, 6, 7, 8)
> >>> tuple
> (1, 2, 3, 4, 5, 6, 7, 8)
Ah, but that is not what the OP did! Look:
" frug = frug , rug "
Let's expand on this a little in the interpreter.
>>> frug = (1, 2, 3, 4)
>>> rug = (5, 6, 7, 8, 9)
>>> frug = frug, rug
Remember Python evaluates the right-hand expression in its entirety first,
then binds the result to the left side. What happens in that third line can
be better understood if entered like this:
>>> frug = (frug, rug)
Keep in mind that Python only requires parentheses around a tuple in cases
where not doing so could be misinterpreted. Here we created a new tuple and
assigned it to frug. Look at the new value of frug:
>>> frug
((1, 2, 3, 4), (5, 6, 7, 8, 9))
You have a tuple which contains these two tuples: (1, 2, 3, 4) and (5, 6, 7,
8, 9). If you mistakenly assume that frug was the concatenation of the two
tuples, and attempt to access, oh say, the fourth element (index=3) you'd
get an exception:
>>> frug[3]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: tuple index out of range
That's because, as stated previously, frug only has two elements. You're
going to need to do a little more work to access the individual elements.
>>> frug[0]
(1, 2, 3, 4)
>>> frug[1]
(5, 6, 7, 8, 9)
>>> frug[0][0]
1
>>> frug[1][0]
5
Previous replies have provided a solution (concatenation). I just wanted to
point out a possible source of misunderstanding. Hope that helps someone!
Scott
More information about the Tutor
mailing list