jeudi 3 juin 2021

Why is python printing a whole list when I'm asking it to iterate through the list?

What about this code is causing it to print a whole list for i rather than each item in the list?

population = []
total = 0
for i in range(1, 31):
    population.append(i)
while total < 101:
    sample = [random.sample(population, 5)]
    for i in sample:
        print(i)
        print(sample.count(i))
    total += 1

It is printing the list of five numbers randomly sampled from the 30 generated in the "population" list and looks like this:

[12, 3, 14, 16, 9]
1

BUT if I just do the exact same code with a non randomly-generated "sample" list, it prints the numbers as iterated on separate lines:

sample = [12, 3, 14, 16, 9]
    for i in sample:
        print(i)
        print(sample.count(i))

Printed result:

12
1
3
1
14
1
16
1
9
1

What's the difference? Thank you!




Aucun commentaire:

Enregistrer un commentaire