dimanche 31 janvier 2021

why does my list keep changing after using for loop to append?

I've created a function that produces n number of random k-combinations of tuples from the list below (example is 5 sets of 6 tuples). Though the function works as expected, every time I run the script it overwrites what was previously appended to rand_list.

list_a=[(0, 1), (0, 2), (0, 5), (0, 10), (0, 20), (0, 50), (0, 100), (2, 1), (2, 2), (2, 5), (2, 10), (2, 20), (2, 50), (2, 100), (5, 1), (5, 2), (5, 5), (5, 10), (5, 20), (5, 50), (5, 100), (10, 1), (10, 2), (10, 5), (10, 10), (10, 20), (10, 50), (10, 100), (20, 1), (20, 2), (20, 5), (20, 10), (20, 20), (20, 50), (20, 100), (50, 1), (50, 2), (50, 5), (50, 10), (50, 20), (50, 50), (50, 100), (100, 1), (100, 2), (100, 5), (100, 10), (100, 20), (100, 50), (100, 100)]
import random
rand_list=[]

def rand_gen(n):

i=[random.choices(list_a, k=6) for r in range(n)]
    for x in i:
        if x not in rand_list:
            rand_list.append(x)

rand_gen(5)
print(rand_list)

e.g. first run output:

print(rand_list) >>> [[(0, 50), (50, 10), (10, 20), (10, 1), (20, 20), (5, 2)], [(0, 5), (50, 5), (0, 50), (5, 20), (5, 100), (0, 10)], [(100, 2), (50, 10), (10, 2), (50, 100), (0, 1), (20, 10)], [(20, 2), (50, 2), (20, 100), (50, 2), (20, 10), (5, 5)], [(100, 5), (0, 20), (100, 10), (50, 100), (5, 1), (10, 50)]]

second run output

print(rand_list) >>> [[(2, 1), (5, 5), (10, 1), (5, 100), (0, 5), (0, 100)], [(5, 10), (100, 1), (100, 100), (2, 10), (0, 5), (5, 50)], [(50, 2), (5, 100), (0, 5), (100, 5), (10, 50), (20, 1)], [(20, 50), (10, 10), (2, 5), (5, 50), (100, 1), (0, 50)], [(10, 1), (0, 10), (10, 20), (10, 2), (5, 2), (10, 20)]]

How do I get it to stay the same? I want to use rand_list elsewhere but I can't if it just changes every time i run the script and so is not stable. IDE is sublime text if that's relevant.

how do i get the list to be stable i.e. only producing what was in the first run regardless of how many times the script is run?




Aucun commentaire:

Enregistrer un commentaire