Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffling in python

Tags:

python

I'm trying to shuffle an array of functions in python. My code goes like this:

import random

def func1():
    ...

def func2():
    ...

def func3():
    ...

x=[func1,func2,func3]
y=random.shuffle(x)

And I think it might be working, the thing is that I don't know how to call the functions after I shuffle the array!

if I write "y" after the last line, it doesn't do anything!

Thanks

like image 519
Estefania Avatar asked Dec 09 '22 12:12

Estefania


1 Answers

Firstly, random.shuffle() shuffles the list in place. It does not return the shuffled list, so y = None. That is why it does nothing when you type y.

To call each function, you can loop through x and call each function like so:

for function in x:
    function() # The parentheses call the function

Lastly, your functions actually produce a SyntaxError. If you want them to do nothing, add pass at the end of them. pass does absolutely nothing and is put where python expects something.


So altogether:

def func1():
    pass

def func2():
    pass

def func3():
    pass

x = [func1, func2, func3]
random.shuffle(x)
for function in x:
    function()
like image 152
TerryA Avatar answered Dec 14 '22 22:12

TerryA