user3608028
user3608028

Reputation: 37

Swapping a letter in a 2D list in Python

I need to swap a letter with another one in Python. I am using a procedure to achieve this. My code is:

def mapwithtreasure():
    board[plyr_x][plyr_y] ='o'
    board = [w.replace('o', 'X') for w in board]
    print(board)
    return board

An error message pops up saying that I am trying to access a local variable before it has been assigned. The list is called 'board' and if I take out the second line in this procedure...

board = [w.replace('o', 'X') for w in board]

...the procedure runs without flagging up a message saying that I ma trying to access a variable which has not been assigned, even though it is referencing the same name variable name: board.'

I have also tried this method:

def mapwithtreasure():
    board[plyr_x][plyr_y] ='o'
    for n, i in enumerate(board):
        if i=='o':
            board[n]='X'
    print(board)
    return board

But this method doesn't seem to make the required replacement?

Any ideas?

Upvotes: 0

Views: 125

Answers (2)

Christian W.
Christian W.

Reputation: 2660

You have at least two problems by the looks of your question. You are modifying a value on board, which does not exist in that function yet. Either give it to that function via parameter or use global variables (or make it a class and use class variable board).

The second problem is that you cannot use replace() on lists, as you have nested structure, so you'll need nested list comprehension:

>>> board = [['o', 'o', 'o'], ['o', 'o', 'o'], ['o', 'o', 'o']]
>>> board = [[w.replace('o','X') for w in x] for x in board]
>>> board
[['X', 'X', 'X'], ['X', 'X', 'X'], ['X', 'X', 'X']]

Upvotes: 1

eigil
eigil

Reputation: 465

The quick fix: Add global board as the first line in the function.

Since you are assigning a value to board in the function, Python assumes that it is supposed to be a local variable, and it gets confused when you try to modify it before it's created. By adding global board you tell Python to not assume that it is a local variable, but instead look for a global variable of that name and use that.

Upvotes: 0

Related Questions