# [Tutor] Making a better list

Lloyd Hugh Allen lha2@columbia.edu
Sun, 09 Dec 2001 07:29:09 -0500

```Danny Yoo wrote:
>
> ###
> import UserList
> class LooseList(UserList.UserList):
>     def __setitem__(self, key, value):
>         if key >= len(self.data):
>             self.expandList(key - len(self.data) + 1)
>         self.data[key] = value
>
>     def expandList(self, length):
>         for i in range(length):
>             self.append(None)
> ###
>
> Let's see if it works ok:
>
> ###
> >>> l = LooseList(['hello', 'world'])
> >>> l = LooseList(['hello', 'world'])
> >>> l[4] = 'divas'
> >>> l[42] = 'answer to life'
> >>> l
> ['hello', 'world', None, None, 'divas', None, None, None, None, None,
>  None, None, None, None, None, None, None, None, None, None, None, None,
>  None, None, None, None, None, None, None, None, None, None, None, None,
>  None, None, None, None, None, None, None, None, 'answer to life']
> ###
>
> As a warning: this is not to say that I encourage the use of this
> LooseList: I think it's way too loose.  *grin* But it's nice to see that
> we have the power to extend Python this way if we wanted.
>

But if we replace "None" with "0", and make the list two dimensional,
this would be just the ticket for converting a sparse matrix defined by
the dictionary method (i.e., entries that exist have key of index and
value of value) into explicit matrices (two dimensional lists, with zero
as the value of entries that didn't previously "exist").

Or did somebody already uselessize this.

```