[Tutor] Variable help

Kent Johnson kent37 at tds.net
Sun Oct 8 20:25:31 CEST 2006


Tom R. wrote:

> Alternately, how can I use the return of a function as a variables name? eg:
> 
> def choose_player(player):
>     if player == 1:
>         return player1[3
>     if player == 2:
>         return player2[3]
>     if player == 3:
>         return player3[3]
>     if player == 4:
>         return player4[3]
> 
> choose_player(2) = 5

You actually can do this very easily by returning the correct playerx list:

def choose_player(player):
     if player == 1:
         return player1
     if player == 2:
         return player2
     if player == 3:
         return player3
     if player == 4:
         return player4

then the result of choose_player() is a list that you can index normally:
choose_player(2)[3] = 5

This actually looks a lot like the solution with a list of player lists, 
where you would write
players[2][3] = 5

I recommend the list-of-lists solution, but I thought it was worth 
noting that the function version is easy to write.

Kent



More information about the Tutor mailing list