Ananth Upadhya Ananth Upadhya - 4 months ago 14
Python Question

Replacing one number with another in PYTHON

I have declared a board array which is 10*10.I am reading the elements of the board which are 0, 1, and 2. After reading my board looks somewhat like this (shorter version 4*4)

0 1 0 2
2 1 0 1
0 2 1 0
1 2 1 0


Code:

board = []
for i in xrange(0, 10)
board.append(raw_input())


now i want to change all occurences of 0 to 1. I am not able to change it..what should i do..please write the modified code..(getting error as immutable)

Thanks for the answer it got changed.I should first covert the list to string then use replace function

Answer

As I understood, you have a list and just want to replace all 0's with 1's right? If it's like that, you can try to convert that list to string and use the replace method. Like: board = str(board) and then board = board.replace('0','1'). And then convert back to list with eval built-in function. But this may be too slow for big lists .

UPDATE >> If you do not want to use strings you can also code this: If it is a 2d list like: L = [[1, 1, 0], [0, 2, 1], [0, 0, 0]] then:

for x in L:
    for y in x:
        if y == 0:
            x[x.index(y)] = 1

And if it is just a common list like L = [1, 0, 2, 1, 0, 1] then:

for x in L:
    if x == 0:
        L[L.index(x)] = 1