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)
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.
Note: Backticks are not single quotes.
To answer your question: You are correct about Scenario 1 being incorrect, but Scenario 2 is not doing anything similar to it.
In Scenario 2 the variable x0 has been declared, and is a value. Therefore, in this line:
x[100:200, :] = x0
the values of each of the matrix members between cols 100-200, and all the rows, are given the value of x0.
b + a = answer
answer is never declared to equal a number, and b+a on the left does not become another variable, it becomes a value. Therefore, is invalid.
Thank you very much for your explanation, it does make a little more sense, However, please excuse me for misunderstanding - but would line 2 in the below code be useless then, because the code is assigning a matrix to x0 in line 2, but then it is being over-written or assigned a new value on line 3 ? so what was the purpose of line 2
Ah, this is a very important thing, when working with a large amount of data. Here is what is going on/should be happening:
Line 1 is telling your program ahead of time: “This variable x is going to be a matrix of size m x n. Prepare this amount of space in memory to store the data.”
Line 2 is just some other matrix, serving as a way to make reading the code slightly easier.
Line 3 is rewriting the values of x from line 1, using the values in x0.
x0 stays the same. It is not over-written. x is over-written, but it has been initialised, to avoid the scenario where you are increasing the size of x by appending new values to it (this is bad for efficiency, as well as memory). Instead, every element of x has already been allocated a place in memory, and the value of the element is just being changed.
Essentially, the above could be written as:
x = -2*np.random.rand(200,2)
x[100:200, :] = 1 + 2*np.random.rand(100,2)
Now, you are only re-writing half of the values of x, but the memory pre-allocation is still useful.
I hope this was clear. It sounded muddled in my head.