0

I was studying this code:

"""Processes an encoded symbol together with its coefficients."""
def consume_packet(self, coefficients, packet):    
    if not self.is_fully_decoded():
        # add new symbol to decoder matrix and packet vector
        self.coefficient_matrix[self.num_independent][0:self.num_symbols] = coefficients
        self.packet_vector[self.num_independent] = packet

To help understand the two lines of code inside the if block, I tried this:

packet = [1, 2, 4]
num_symbols = 3
coefficient_matrix = [1, 2, 4, 5, 6, 7]
coefficient_matrix[0][0:num_symbols] = packet # I think this is supposed to extract the packet
print(coefficient_matrix[0])
print(coefficient_matrix[0][0:num_symbols])

but I got an error that says int object does not support item assignment.

Why does this happen?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 1
    `coefficient_matrix[0]` is just `1`, and you can't do `1[0:num_symbols]`. I think what you want is `coefficient_matrix[0:num_symbols]`. – Samwise Jan 13 '23 at 03:27
  • `var[index] = value` assigns, or puts, `value` into some sort of 'slot' in the `var` object. Actual behavior depends on what `var` is. This syntax can be used to assign values in a `list`, in a `dict`, or a numpy array (and more). In your test `coefficient_matrx` is a list, and `coefficient_matrix[0]` is an element of that, in this case a number. No further indexing is possible. `coefficient_matrix[0]=23` assigns a new value to the list. Do you have a introduction to python book? Read it? – hpaulj Jan 13 '23 at 03:46
  • @hpaulj thanks a lot for your detailed explanation. I wonder what I was thinking in the first place. I am laughing at myself – Patrick Enenche Jan 13 '23 at 04:19
  • Welcome to Stack Overflow. Generally, code like this is expected to be given a Numpy array, rather than a built-in Python list - I notice you tagged the question `numpy` yourself, so I assume you have some awareness of this. At any rate, having multiple `[]` like this implies that the data should have multiple "dimensions", so a simple list won't do. `x[y][z]` means to do `x[y]` first, and then do `[z]` with whatever the result was. It's not clear what is actually confusing about this, but I tried to link some existing questions on the right topic. – Karl Knechtel Jan 16 '23 at 08:09

0 Answers0