leonardik
leonardik

Reputation: 131

Python -How to extract last list value to another separate list?

I need a code which created lists then extracts last value and adds them to separate list. Current code returns [0, 1, 3, 8] [8] [0, 6, 15, 20] [20] [0, 1, 7, 12] [12] [0, 8, 10, 17] [17] [0, 5, 12, 13] [13] while required format must be [0, 1, 3, 8] [0, 6, 15, 20] [0, 1, 7, 12] [0, 8, 10, 17] [0, 5, 12, 13]

[8,20,12,17,13]

import numpy as np

for j in range(5):
    d=[]
    a=[0]

    for b in range(3):
        value = np.random.randint(1,10)
        b=a[-1]+value
        a.append(b)
    d.append(a[-1])

    print(a)
    print(d)
 

Upvotes: 0

Views: 98

Answers (1)

UnprolificToad
UnprolificToad

Reputation: 119

You defined d=[] inside the loop, so d will be initialized to an empty list at each iteration. Move it to outside the loop.

import numpy as np

d=[]
for j in range(5):
    a=[0]

    for b in range(3):
        value = np.random.randint(1,10)
        b=a[-1]+value
        a.append(b)
    d.append(a[-1])

    print(a)

print(d)

Upvotes: 1

Related Questions