Home > Software design >  Python: append to list
Python: append to list

Time:10-07

Please forgive me if this question is ridiculously simple, I am an absolute newbie.

I am busy looking at a python tutorial, and this one is to generate a Random Walk. It works, but the tutorial isn't very clear on why it works...

It is to simulate a coin toss 10 times, it is either heads or tails (0 or 1). The list then gets updated with each toss, but keeps track of how many times 1 was found

import numpy as np

np.random.seed(123)

tails = [0]

for x in range(10):
    print(x)
    coin = np.random.randint(0, 2)
    print(coin)
    tails.append(tails[x]   coin)
    print(tails)

It is the working of this line that I don't grasp:

tails.append(tails[x]   coin)

The output I get is:

0
0
[0, 0]
1
1
[0, 0, 1]
2
0
[0, 0, 1, 1]
3
0
[0, 0, 1, 1, 1]
4
0
[0, 0, 1, 1, 1, 1]
5
0
[0, 0, 1, 1, 1, 1, 1]
6
0
[0, 0, 1, 1, 1, 1, 1, 1]
7
1
[0, 0, 1, 1, 1, 1, 1, 1, 2]
8
1
[0, 0, 1, 1, 1, 1, 1, 1, 2, 3]
9
0
[0, 0, 1, 1, 1, 1, 1, 1, 2, 3, 3]

For the first iteration x = 0, coin = 0 and the list is then updated to be [0, 0]. In iteration 1 the coin is 1 and then the list is updated to be [0, 0, 1]. Iteration 2 is where I don't understand. Coin is zero, but 1 ends up at the back of the list. This is the expected behavior, as it shows that over the coin tosses up until now, 1 has only been found once, but I do not understand why.

Can anyone help me?

CodePudding user response:

tails.append(tails[x]   coin)

the crucial part is what happens in the brackets

Since tails already has one element (tails = [0]), tails[x] is essentially "give me the previous result" or also "give me the last result in the list"

Thus tails[x] coin adds the current coin flip to the previous result. Effectively tails is a list describing "how many tails were chosen at this timestep".

[0, 0, 1, 1, 1, 1, 1, 1, 2, 3] = "at timestep 8 there was the second coinflip resulting in "tails"

  • Related