Python -Assigning variables help

Hi, Please can somebody help me, Please tell me how the below is different.

Scenario 1:

a = 3

b = 2

b + a = answer


Scenario 2

x = -2 * np.random.rand(200,2)

x0 = 1 + 2 * np.random.rand(100,2)

x[100:200, :] = x0

It is understood that a variable cannot be assigned at the end of a statement, So my scenario 1 wouldn’t work - which I understand, however how is it allowed in scenario 2( which i copied from a code tutorial)

>a variable cannot be assigned at the end of a statement

This is not quite correct. A more accurate statement would be “storing a value takes place on the left side of an equals sign”.  What is on the left side of the equals sign is not limited to variables: if the left side is any sort of storage location, it is allowed.

In scenario 1, “b + a” is an expression, and does not result in a storage location.

In scenario 2, “x[100:200, :]” is an expression which results in a storage location. In the assignment, the values from the storage location “x0” are being placed into the storage location “x[100:200, :]” and not the other way around.

Scenario 2 is quite more complicated than scenario 1 in that both “x” and “x0” involve 100s of storage locations. Python allows assigning complex storage objects, not just simple variables.

1 Like

Scenario 1:

There are two problems with the statement b + a = answer

  1. answer is not defined anywhere in the script

2)even if it is defined anywhere in the script, we can’t assign to an operator.

Scenario 2:

I understand your point of view here,

but the statement x[100:200, :] = x0.

The left side of the statement is a slicing operation. We use a concept called slice assignment. Slice assignment means assigning a value into an element or slice into an array contained by a local variable.

Here x0 is a numpy array containing 100 elements and we are overwriting the values of x from index 100 to 200 with these 100 elements.