RDSE / python list assignment question

This is probably something I don’t understand about python, because it obviously works, I just don’t understand how. I’m porting the RDSE from python to javascript for a visualization, and I can’t understand this array index assignment highlighted below:

The output is a list of zeros at this point, and the line above looks like it should assign one of those zeros to one. But the mapBucketIndexToNonZeroBits function returns a list of indexes, not a single integer:

(The bucketMap above contains values that are lists of integers.) The output of self.mapBucketIndexToNonZeroBits(bucketIdx) is a list itself, indicating to me that multiple list elements are being assigned to 1 in this line:

output[self.mapBucketIndexToNonZeroBits(bucketIdx)] = 1

But I can’t seem to do this in my python REPL. For example:

output = [1,2,3,4,5,6,7,8,9,0]
output[[0,1,2,3]] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not list

I am missing something here, does anyone see what it is?

The output in the RDSE is a numpy array. Yours is just a regular list.

>>> foo = [0, 0, 0, 0]
>>> bar = [1, 2]
>>> foo[bar] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not list

>>> foo2 = numpy.zeros(4)
>>> foo2[bar] = 1
>>> foo2
array([ 0.,  1.,  1.,  0.])


@mrcslws you just beat me! @rhyolight the documentation should be improved to specify this is a numpy array.

And FWIW the mapBucketIndexToNonZeroBits() method could be simplified if self.bucketMap were a defaultdict. I.e. [self.bucketMap = defaultdict(self._createBucket(index)).

1 Like

See http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#index-arrays for explanation wrt numpy.

1 Like

I’ll do that.

I don’t understand what you mean. The bucket map is assigned to an empty {} when initialized.

Yes, but this could be improved if it’s initialized as a defaultdict: self.bucketMap = defaultdict(self._createBucket(index)). Then four of the nine lines of mapBucketIndexToNonZeroBits() can be deleted.
Just me being picky :smile:

1 Like