[Tutor] creating a list of data . . .

Jeff Shannon jeff at ccvcorp.com
Tue Aug 26 10:51:50 EDT 2003


Scott Widney wrote:


>>>>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))


What makes this even worse is that the O.P. spoke of having 14 data 
elements that should end up in this tuple.  If we presume that this 
means the above was done 14 times....

 >>> frug = ()
 >>> frug
()
 >>> for n in range(14):
... 	frug = frug, n
... 	
 >>> frug
(((((((((((((((), 0), 1), 2), 3), 4), 5), 6), 7), 8), 9), 10), 11), 
12), 13)
 >>> frug[0][0][0][0][0][0][0][0][0][0][0][0][0][0]
()
 >>>

Well, that's a bit ugly.  It's possible to nest tuples (and lists) 
arbitrarily deep, but that doesn't mean it's a good idea.  (The Zen of 
Python, line 5 -- "Flat is better than nested.")  However, note that 
the only change necessary to make the above into something reasonable 
is to change the nesting into addition:

 >>> frug = ()
 >>> for n in range(14):
... 	frug = frug + (n,)
... 	
 >>> frug
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
 >>>

Note that I had to make n into a one-element tuple before I could add 
it to the existing tuple, because sequences can only be added to other 
sequences of similar type.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Tutor mailing list