1

I have three lists inside a list. I want to change a specific element of a specific list. So lets say the second list, first element. I tried it like this:

Here is the whole thing, I am just learning how to program so don't judge me :)

class Board:
#creates visible playing board
global rows
rows = []
def create_row(self):
    row1 = []
    while len(row1) <= 4:
        if len(row1) <= 3:
            row1.append("x")
        else:
            row1.append("\n")
    rows.append(row1)

def input(self):
    print "Enter a colum num"
    height = int(raw_input(">"))
    height = height - 1
    print "Enter a row num"
    width = raw_input(">")
    print rows.__class__
   # for i in rows[height]:
       # i[height] = 'a'




def display(self):
    for i in rows:
        for m in i:
            print m,



row1 = Board()
row1.create_row()

row2 = Board()
row2.create_row()

row3 = Board()
row3.create_row()

row4 = Board()
row4.create_row()

row4.display()
row4.input()
row4.display()
5
  • Can you show us what list you're using? The error is because you're trying to assign to an object that can't be changed. Commented Apr 17, 2011 at 1:21
  • Try printing rows.__class__ and tell us what comes out Commented Apr 17, 2011 at 1:26
  • <type 'list'> is what comes out Commented Apr 17, 2011 at 1:27
  • rows is unlikely to be the problem. @bipolarpants, please show the whole traceback, which should confirm that the error is in the line i[height] = 'a'. Before that line, insert print type(i), repr(i) and show us what the result is. Commented Apr 17, 2011 at 4:01
  • I'll just post all the code up, it's pretty short. Commented Apr 17, 2011 at 16:32

1 Answer 1

2

Trace this through - assume we enter '3' when prompted, so height = 2; then

for i in rows[2]:

the first value of i is 'x'

    'x'[2] = 'a'

and this gives you your error - you cannot change a character in the string because strings are immutable (instead you have to construct a new string and replace the old one).

Try the following instead:

def getInt(msg):
    return int(raw_input(msg))

row = getInt('Which row? ')
col = getInt('Which col? ')

rows[row-1][col] = 'a'

Try the following instead:

def getInt(msg, lo=None, hi=None):
    while True:
        try:
            val = int(raw_input(msg))
            if lo is None or lo <= val:
                if hi is None or val <= hi:
                    return val
        except ValueError:
            pass

class GameBoard(object):
    def __init__(self, width=4, height=4):
        self.width  = width
        self.height = height
        self.rows   = [['x']*width for _ in xrange(height)]

    def getMove(self):
        row = getInt('Please enter row (1-{0}): '.format(self.height), 1, self.height)
        col = getInt('Please enter column (1-{0}): '.format(self.width), 1, self.width)
        return row,col

    def move(self, row, col, newch='a'):
        if 1 <= row <= self.height and 1 <= col <= self.width:
            self.rows[row-1][col-1] = newch

    def __str__(self):
        return '\n'.join(' '.join(row) for row in self.rows)

def main():
    bd = GameBoard()

    row,col = bd.getMove()
    bd.move(row,col)

    print bd

if __name__=="__main__":
    main()
Sign up to request clarification or add additional context in comments.

2 Comments

"This gives you your error": The CPython error message changed in 2.5 from the fixed "object does not support item assignment" to variable -- in this case "'str' object does not ...". The OP says he got "can't assign to immutable object". How do you account for that?
@John Machin: I don't think we know which version of which implementation the OP is using. For example, Jython contains the original error message.

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.