Doubt random.shuffle (), returns None (within print)

1

Because when random.shuffle() used within the string returns None ?

I discovered afterwards that you can use shuffle to get out of print and put it on a single line but I do not understand why it hangs.

Sample code

from random import shuffle

n1= str (input ('Digite o nome do primeiro aluno: '))
n2= str (input ('Digite o nome do segundo alino: '))
n3= str (input ('Digite o nome do terceiro aluno '))
n4= str (input ('Digite o nome do quarto aluno: '))
l= [n1,n2,n3,n4]

print ('A ordem dos trabalhos será: {}' .format(shuffle (l) ))
    
asked by anonymous 03.02.2018 / 13:10

1 answer

2

By documentation you see that random.shuffle shuffles the list itself and does not return no value:

  

(..) Shuffle the sequence x in place. (...)

Starting from a concrete example of a list of notes:

l = [15,2,20,12]

If you do:

shuffle(l)

You're shuffling the list. And depending on how it was shuffled it could look like this:

>>> l
[2, 15, 12, 20]

The function, however, does not return any value or any new shuffled list, it only changes the list received by parameter. So it will not make sense to do:

.format(shuffle (l) )

The solution to your code is exactly as you mentioned:

from random import shuffle

n1= str (input ('Digite o nome do primeiro aluno: '))
n2= str (input ('Digite o nome do segundo alino: '))
n3= str (input ('Digite o nome do terceiro aluno '))
n4= str (input ('Digite o nome do quarto aluno: '))
l= [n1,n2,n3,n4]
shuffle (l) # só shuffle

print ('A ordem dos trabalhos será: {}' .format(l)) # só mostrar

You can even see the implementation of the shuffle function by referring to your source code :

def shuffle(self, x, random=None):
    """Shuffle list x in place, and return None.
    Optional argument random is a 0-argument function returning a
    random float in [0.0, 1.0); if it is the default None, the
    standard random.random will be used.
    """

    if random is None:
        randbelow = self._randbelow
        for i in reversed(range(1, len(x))):
            # pick an element in x[:i+1] with which to exchange x[i]
            j = randbelow(i+1)
            x[i], x[j] = x[j], x[i]
    else:
        _int = int
        for i in reversed(range(1, len(x))):
            # pick an element in x[:i+1] with which to exchange x[i]
            j = _int(random() * (i+1))
            x[i], x[j] = x[j], x[i]

Notice how nowhere else in this function is a return made.

Notice the comment made at the beginning of the function:

  

"" Shuffle list x in place, and return None.

    
03.02.2018 / 13:37