0
Could you please explain me the behaviour of append in function?
I tried to write down more information and question to my test code here: https://code.sololearn.com/c76hL5fupqRT/?ref=app I am new to programming so I don't know if this is only python behaviour or not. Thanks.
3 Answers
+ 8
test_01 part executes last() method just once and so appends to a only once, too. Before this, a is [0], b is assigned the last element of a, so 0 and x is equal to a, so [0]. After the test, b is returned 0 and both a and x is equal to [0, 1].
test_02 executes the last method twice. So first, the iteration goes exactly like in test_01. But when you print to screen, you execute last() the second time. b is assinged the last value of x (being equal to [0, 1]), so 1. And this is what is returned and printed. By that time, a and x are qual to [0, 1, 2].
+ 1
You assign
b=x[-1] with list x = [0].
In an one element list
index 0 = index -1,
hence b = 0.
Then you append value b+1 to x and then return b.
See? After you assign b = 0, you don't touch b anymore before returning b.
Appending a new item to x is completely irrelevant for b's value, even if that value is calculated with b.
0
OK. Thank you.