Jumping around when assigning elements

Cameron Laird claird at lairds.com
Mon Dec 15 19:35:02 EST 2003


In article <brljag$ihk$01$1 at news.t-online.com>,
Peter Otten  <__peter__ at web.de> wrote:
>Matthew Sims wrote:
>
>> Is there anyway to assign to an element that wasn't defined in the
>> beginning? Like if I wanted element 5 assigned but not element 4
>> without using "" or None?
>
>You can write your own class:
>
>class GrowingList(list):
>    def __init__(self, seq, default=None):
>        list.__init__(self, seq)
>        self.default = default
>    def __setitem__(self, index, value):
>        if index >= len(self):
>            self.extend([self.default]*(index - len(self)))
>            self.append(value)
>        else:
>            list.__setitem__(self, index, value)
>
>
>g = GrowingList(["alpha", "beta", "gamma"])
>g[7] = "omega"
>print g
>
>This is a partial implementation, only g[index] = value will work.
>
>> I'm currently re-writing a Perl script into Python and with Perl I was
>> free to assign any element in the array without having to fill in the
>> previous elements. I can't seem to do that in Python...unless I'm
>> doing it wrong.
>
>As already pointed out, a mechanical translation will yield substandard
>results. As you did not describe the problem you are solving with the
>"autogrowing" list, there is little chance for us to come up with a better
>or at least more idiomatic approach.
			.
			.
			.
We've probably convinced Mr. Sims that Python (and
object-oriented programming) is really, really hard,
particularly compared to Perl:  we have to write
hairy Class definitions just to do the simplest
things.

I think there's a fair probability this is all a
misunderstanding, and that what Mr. Sims truly wants,
although he doesn't realize it, is simply a dictionary, 
rather than a list.  Mr. Sims, how would you feel if I
said you should be using a Perl "hash" rather than an
"array"?
-- 

Cameron Laird <claird at phaseit.net>
Business:  http://www.Phaseit.net




More information about the Python-list mailing list