DapperDuck
DapperDuck

Reputation: 2859

Simplify series of elif statements in Python

I'm creating a tic-tac-toe ai program with a board formatted like this:

board = [['X','O','X'],[' ','O',' '],[' ',' ',' ']]

I have a series of elif statements like this, which checks if a side is empty, and if so return the board position of that side:

if board[1][0] == ' ':
    return 1, 0
elif board[1][2] == ' ':
    return 1, 2
elif board[0][1] == ' ':
    return 0, 1
else:
    return 2, 1

Since the condition is the same, is there a faster way of doing this?


Update 1: After implementing kaya3's answer the program runs 0.05 - 0.2 seconds faster

Upvotes: 0

Views: 56

Answers (1)

kaya3
kaya3

Reputation: 51063

If you want to do the same thing for a series of different values, put them in a list, and then loop over it:

sides = [(1, 0), (1, 2), (0, 1), (2, 1)]

for x, y in sides:
    if board[x][y] == ' ':
        return x, y

Upvotes: 3

Related Questions