Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #63114
| From | "Frank Millman" <frank@chagford.com> |
|---|---|
| Subject | Re: Creating a list with holes |
| Date | 2014-01-04 09:00 +0200 |
| References | <CACwCsY5P47-dB1NLQTUTQ=0aF6B+-M3y4hCxcUGmcVmHM8=-xQ@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.4894.1388818829.18130.python-list@python.org> (permalink) |
"Larry Martell" <larry.martell@gmail.com> wrote in message news:CACwCsY5P47-dB1NLQTUTQ=0aF6B+-M3y4hCxcUGmcVmHM8=-xQ@mail.gmail.com... >I think I know the answer is no, but is there any package that allows > creating a list with holes in it? E.g. I'd want to do something like: > > x[10] = 12 > x[20] = 30 > > I'm thinking of something like defaultdict but for lists (I know > that's very different, but ... ) > > Thanks! > -larry Just out of interest, I asked the same question on this list many years ago, and someone actually gave me an answer. It was something like the following - >>> class MyList(list): ... def __getitem__(self, pos): ... try: ... return list.__getitem__(self, pos) ... except IndexError: ... return None ... def __setitem__(self, pos, value): ... try: ... list.__setitem__(self, pos, value) ... except IndexError: ... diff = pos - list.__len__(self) ... self.extend([None] * diff) ... self.append(value) ... >>> ml = MyList() >>> ml[3] >>> ml[3] = 'a' >>> ml [None, None, None, 'a'] >>> I wanted it because I was familiar with it from a previous language I had used. As is turns out, I never actually used it, but I was impressed! Frank Millman
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Creating a list with holes "Frank Millman" <frank@chagford.com> - 2014-01-04 09:00 +0200
csiph-web