Estefania
Estefania

Reputation: 95

Shuffling in 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

Upvotes: 4

Views: 167

Answers (1)

TerryA
TerryA

Reputation: 59974

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

Upvotes: 14

Related Questions