0

I am a beginner learning python. I have a problem with this for loop.

I am trying to a search loop for pc to track the move made by the player (human) and to anticipate the next move in a tic tac toe game.

As a result, I create a for loop to append the moves made by the player(human) but something strange happens

    lst = [ [ "X",[], [] ],
    [ [], "X", []   ],
    [ [], "X", []   ] ]
    temp_lst = []
    for i in lst:
        lst_1 = []
        for j  in i:
            if j  == "X":
            lst_1.append(lst.index(i))
            print(lst.index(i))
            lst_1.append(i.index(j))
            print(i.index(j))
        temp_lst.append(lst_1)

  print (temp_lst)

The results on my IDLE is:

    0
    0
    1
    1
    1
    1
   [[0, 0], [1, 1], [1, 1]]

Note that the position of the "X" IN THE MIDDLE and the "X" int the last list is the same which would not be. This is my problem. Note that when I change the lst to:

     lst = [ [ "X",[], [] ],
    [ [], "X", []   ],
    [ [], [], "X"  ] ]       

   result: [[0, 0], [1, 1], [2, 2]]

The result from python shows the correct position of the last "X" but in the previous one it gave the strong position for the last "X"

Please help thank you

2
  • Your expected output for the last iteration is [1,2]? Commented Jul 20, 2016 at 4:52
  • Your code's indentation is wrong. This is important in python and does change what your code outputs. You should correct it. Commented Jul 20, 2016 at 4:57

2 Answers 2

1

In the outer loop, on the last iteration, you are testing for the index of the literal array: [[],["X"],[]]. So Python finds the first one by equality: which is the same as the second item.

Sign up to request clarification or add additional context in comments.

Comments

0

As Jeff Meatball Yang said index works so that it find first occurance in list. I would do something like that

lst = [["X", [], []],
   [[], "X", []],
   [[], "X", []]]
temp_lst = []

for i in range(len(lst)):
    lst_1 = []
    for j in range(len(lst[i])):
        if lst[i][j] == "X":
            lst_1.append(i)
            print(i)
            lst_1.append(j)
            print(j)
    temp_lst.append(lst_1)

print (temp_lst)

The result of that code is: [[0, 0], [1, 1], [2, 1]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.