Search code examples
pythonlist-comprehensiontic-tac-toe

Nested list comprehensions combined with an if


I am trying to loop through a list which contains my game field (TicTacToe). This list looks like:

['X', '_', '_']
['O', 'X', '_']
['_', 'O', 'X']

I wanted to generate a list containing the indicies of all Xs or Os. My function doing that looks like that:

indicies = []
for x,y in enumerate(self.gameField):
    for b,c in enumerate(y):
        if c == 'X':
            indicies.append((x,b))

This is working fine, but I want to use list comprehension for doing the same thing. I figured, that this would might work:

indicies = [[(x,b) for b,c in enumerate(y) if c == 'X'] for x,y in enumerate(self.gameField)][0]

But it didn't work out like expected.

Tutorials and StackOverflow couldn't help me in understanding the list comprehension of nested lists. Perhaps somebody can tell me the right way or point me to a good tutorial.


Solution

  • The comprehension version of your loop is

    [(x,b) for (x,y) in enumerate(self.gameField)
         for (b,c) in enumerate(y) if c=='X']
    

    That's one list comprehension with two for clauses, rather than one list comprehension inside another list comprehension.