Creating a list with holes

Chris Angelico rosuav at gmail.com
Fri Jan 3 10:37:05 EST 2014


On Sat, Jan 4, 2014 at 2:19 AM, Larry Martell <larry.martell at gmail.com> wrote:
> 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 ... )

Depending on what exactly you need, it's probably worth just using a
dict. In what ways do you need it to function as a list? You can
always iterate over sorted(some_dict.keys()) if you need to run
through them in order.

Alternatively, if you expect to fill in most of the elements, it's
possible you'd be happier working with a subclass of list that
auto-expands by filling in the spare space with a singleton meaning
"no element here". The code probably exists somewhere, but if not, it
wouldn't be hard to write. Then it'd be a list, but you can start with
it empty and assign as you describe above.

What's the use case? I expect that one or the other of those options
would cover most cases, but maybe yours is different.

ChrisA



More information about the Python-list mailing list