1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Issue with Inner Loop Modifying Outer Loop Variables in Python

Discussão em 'Python' iniciado por Stack, Maio 6, 2025.

  1. Stack

    Stack Membro Participativo

    I am having a problem where an inner loop rewrites variables in the outer one, specifically when working with a list representing a Tic-tac-toe board. I want to place "X" in each empty position one at a time without modifying the already modified board. However, it seems that the inner loop keeps affecting the outer loop variable and variables that have something with it.(positions and copies of the variable)

    Here’s a snippet of my code:

    def occurrences(s, lst):
    return (i for i, e in enumerate(lst) if e == s)

    positions = [[" ", " ", " ", " ", " ", " ", " ", " ", " "]]

    for board in positions:
    for i in range(board.count(" ")):

    occ = list(occurrences(" ", board))[0]
    board[occ] = "X"
    print(board[0:3])
    print(board[3:6])
    print(board[6:])
    print("---------------------")


    Expected Output:

    ['X', ' ', ' ']
    [' ', ' ', ' ']
    [' ', ' ', ' ']
    ---------------------
    [' ', 'X', ' ']
    [' ', ' ', ' ']
    [' ', ' ', ' ']
    ---------------------
    [' ', ' ', 'X']
    [' ', ' ', ' ']
    [' ', ' ', ' ']
    ---------------------
    ...


    Actual Output:

    ['X', ' ', ' ']
    [' ', ' ', ' ']
    [' ', ' ', ' ']
    ---------------------
    ['X', 'X', ' ']
    [' ', ' ', ' ']
    [' ', ' ', ' ']
    ---------------------
    ['X', 'X', 'X']
    [' ', ' ', ' ']
    [' ', ' ', ' ']
    ---------------------
    ...


    Question: I expected the output to show "X" being placed in each empty position one by one, without modifying previous placements. However, it seems that each iteration of the inner loop is affecting the board variable from the outer loop.

    I understand that there are different ways to approach this problem, but I would like to know why Python behaves this way and how I can prevent this from happening.

    Any insights or suggestions would be greatly appreciated!

    Continue reading...

Compartilhe esta Página