tags:

views:

142

answers:

2

I need a list with the following behavior

>>> l = SparseList()
>>> l
[]
>>> l[2] = "hello"
>>> l
[ None, None, "hello"]
>>> l[5]
None
>>> l[4] = 22
>>> l
[ None, None, "hello", None, 22]
>>> len(l)
5
>>> for i in l: print i
None
None
"hello"
None
22

Although it can "emulated" via a dictionary, it's not exactly the same. numpy array can behave this way, but I don't want to import the whole numpy for something like this. Before coding it myself, I ask if something similar exists in the standard library.

A: 

You can just copy and paste the code from numpy.

ygd
:D ...............
Stefano Borini
+3  A: 

Here's minimal code to pass your given examples (with indispensable adjustments: you expect weird spacing and quoting, 'None' to be printed out at the prompt without a print statement, etc etc):

class SparseList(list):
  def __setitem__(self, index, value):
    missing = index - len(self) + 1
    if missing > 0:
      self.extend([None] * missing)
    list.__setitem__(self, index, value)
  def __getitem__(self, index):
    try: return list.__getitem__(self, index)
    except IndexError: return None

__test__ = dict(allem='''
>>> l = SparseList()
>>> l
[]
>>> l[2] = "hello"
>>> l
[None, None, 'hello']
>>> print l[5]
None
>>> l[4] = 22
>>> l
[None, None, 'hello', None, 22]
>>> len(l)
5
>>> for i in l: print i
None
None
hello
None
22
''')
import doctest
doctest.testmod(verbose=1)

I imagine you'll want more (to support negative indices, slicing, and whatever else), but this is all your examples are implicitly specifying.

Alex Martelli
I'm speechless. I did not expect the code :) Thanks :)
Stefano Borini
However, this means that it does not exist in the standard library... may I include your code in the wavemol (BSD) library ?
Stefano Borini
@Stefano, sure, see http://meta.stackoverflow.com/questions/13976/who-owns-the-copyright-to-sofu-content : "user contributed content licensed under cc-wiki with attribution required" per Jeff Attwood's answer (I believe the BSD license is compatible w/that, but I'll be happy to relicense it to you otherwise as needed!-).
Alex Martelli