Random Hoice and shuffle with different behaviors

Asked

Viewed 143 times

5

I’m testing some codes with the module random and I noticed a difference in behavior between random.choice() and random.shuffle(). Following the codes I’m training:

import random

alunos = ['Fernando', 'Paula', 'João', 'Maria']

a = random.choice(alunos)

print(a)

And:

import random

alunos = ['Fernando', 'Paula', 'João', 'Maria']

random.shuffle(alunos)

print(alunos)

The strange thing is that if I use the random.choice() without putting it into the variable a, does not work, it returns the entire list.

Already the random.shuffle() gives me the expected result even if I’m not in a variable. I’m doing something wrong?

2 answers

5


According to the documentation module random, random.choice returns one of the elements of the list, chosen randomly. In its first code, this return was placed in the variable a (that is, it contains only one of the elements of the list). But the list itself is not modified, random.choice only takes one of the elements and returns.

The strange thing is that if I use the random.choice() without putting it into the variable a, does not work, it returns the entire list.

If you do not assign the return of random.choice() a variable, its value is lost:

# retorna um dos elementos da lista, mas este não é atribuído a nenhuma variável
random.choice(alunos)
print(alunos) # imprime a lista, sem modificações

That is, the function returned one of the elements, but where was it stored? Nowhere. And how random.choice does not modify the list, it remains unchanged (actually the function does not "return the entire list", what happens is that the list is not modified in this case).


Already random.shuffle shuffles the list by modifying it. That’s why you don’t need a variable to store the result, because the list itself is being modified within the function.

Inclusive, random.shuffle returns None:

print(random.shuffle(alunos)) # imprime "None"

So it doesn’t even make sense to assign your return to a variable.

Anyway, there is this difference in behavior precisely because each one does a different thing.

0

I guess you didn’t read the paperwork:

shuffle() : Randomize the values in the positions of the list itself, ie return in the list itself, which in this case is alunos, running twice for example, the:

1ª vez, teria resultado: alunos = ['Paula', 'Fernando', 'João', 'Maria']
2ª vez, teria resultado: alunos = ['Maria', 'Paula', 'Fernando', 'João']

choice() : Randomly selects only a single value from the inserted list and returns the chosen value for a variable, which in this case would be a, running twice for example, the:

1ª vez: a = Maria
2ª vez: a = João

Source on Shuffle()

Source on Choice()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.