Doubt Random.shuffle() returns None(inside print)

Asked

Viewed 1,697 times

1

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

I found out after you can use shuffle get off the print and put in a single line but did not understand why it lock.

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) ))

2 answers

2


For documentation sees that random.shuffle shuffles the list itself and returns no value:

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

Starting from a concrete example of a list of notes:

l = [15,2,20,12]

If you do:

shuffle(l)

It’s 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 received list per parameter. So it won’t 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 function shuffle consulting 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 this function is made a return.

Note the comment made at the beginning of the function:

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

1

I had the same question. I only had to pass the variable l as a parameter before 'printar'.

from random import shuffle
l = ['n1', 'n2', 'n3', 'n4']
shuffle(l)
print(l)

[n1, n4, n3, n2]

Browser other questions tagged

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