How to loop through array and change its item

Question:

i’m looping through an array and changing its item by a random number between 1 and 10

from time import sleep as wait
from os import system as sys
import random
memory = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

def cls(): sys("cls")

def main():
    for i in memory:
        memory[i] = random.randrange(1,10)
        print(memory)
        wait(0.1)
        cls()
    print("OK")
    input("")

if __name__ == '__main__':
    main()

but it only changes the first item of the array

how can i fix this?

Asked By: legend

||

Answers:

change your for loop :

for i in range(len(memory)):

in your for each loop i always 0 and you refers to first element ..

Answered By: Lior Tabachnik

Because your i is always 0. And you change only the first element.
I also replaced your class method, by print() parameters.
Please try this snippet:

from time import sleep as wait
import random

memory = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]


def main():
    for i, item in enumerate(memory):
        item = random.randrange(1,10)
        memory[i] = item
        print(memory, end="r", flush=True)
        wait(0.1)
    print("OK")
    input("")

if __name__ == '__main__':
    main()
Answered By: JacekK

I am not sure if this is effecient for your case. but it can achieve the output you want.

from time import sleep as wait
from os import system as sys
import random

memory = [0 for _ in range(0, 29)]

def cls(): sys("cls")

def main():
    global memory
    for _ in memory:        
        ran_index = random.randrange(1, 29)
        memory[ran_index] = random.randrange(1,10)
        print(memory)
        memory = [0 for _ in range(0, 29)]
        wait(0.1)
        cls()
    print("OK")
    input("")

if __name__ == '__main__':
    main()

Your loop:

for i in memory:

Has i represent each element of the array in turn. All of those elements are 0.

Thus:

memory[i] = random.randrange(1,10)

Only ever assigns to the first element in memory.

To iterate over the indices of memory:

for i in range(len(memory)):

But really, if you just want 29 random numbers on a list, a list comprehension will do that jobh much more cleanly.

memory = [random.randrange(1,10) for _ in range(29)]
Answered By: Chris
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.