I want to display the last element of a random number.

I want to create something like a life game using random.randint.

But in the following, what method is used for "step"
I don't know how to display "Random numbers from last rolling dice".

There was an instruction such as "-1" for index, but I don't know how to specify it.
↓ (quoted text)


On each iteration, set step equal to the last element in the random_walk list.You can use the index -1 for this.

My code

# Numpy is imported, seed is set
# Initialize random_walk
random_walk = [0]
# Complete the ___
for x in range (100):
    # Set step: last element in random_walk
    step = random_walk [-1]
    # Roll the dice
    dice = np.random.randint (1,7)
    # Determine next step
    if dice<= 2:
        step = step-1
    elif dice<= 5:
        step = step + 1
        step = step + np.random.randint (1,7)
    # append next_step to random_walk
    random_walk.append (step)
# Print random_walk
print (random_walk)
  • Answer # 1

    In Python, you can specify an element from the right side by specifying a negative index.

    >>>lst = ['s', 'p', 'a', 'm']
    >>>lst [-1]
    >>>lst [-2]
    >>>lst [-3]
    >>>lst [-4]

Related articles