derkyzer
derkyzer

Reputation: 161

(Python) Tuple/List Assignment

Currently to assign my variables, I have this:

rows = [[convert[random.randint(0,7)] for _ in range(5)] for _ in range(5)]
printedrows = [("[X]","[X]","[X]","[X]","[X]","  <- V: {}   TOTAL: {}".format(row.count(0), sum(row))) for row in rows]

This creates 5 rows with random values:

('[X]', '[X]', '[X]', '[X]', '[X]', '  <- V: 1   TOTAL: 9') 
('[X]', '[X]', '[X]', '[X]', '[X]', '  <- V: 2   TOTAL: 5') 
('[X]', '[X]', '[X]', '[X]', '[X]', '  <- V: 0   TOTAL: 6') 
('[X]', '[X]', '[X]', '[X]', '[X]', '  <- V: 1   TOTAL: 10') 
('[X]', '[X]', '[X]', '[X]', '[X]', '  <- V: 0   TOTAL: 8')

I would like to reassign the "X"s to numbers so it reads something like:

('[X]', '[2]', '[X]', '[X]', '[X]', '  <- V: 1   TOTAL: 9') 
('[1]', '[X]', '[3]', '[0]', '[1]', '  <- V: 2   TOTAL: 5') 
('[X]', '[X]', '[1]', '[X]', '[X]', '  <- V: 0   TOTAL: 6') 
('[1]', '[X]', '[X]', '[X]', '[2]', '  <- V: 1   TOTAL: 10') 
('[X]', '[3]', '[X]', '[2]', '[X]', '  <- V: 0   TOTAL: 8')

However, when I use this: (example only - the location is user-determined)

convert = {0:0,1:1,2:2,3:3,4:0,5:1,6:2,7:1}

printedrows[y][x] = rows[y][x]
TypeError: 'tuple' object does not support item assignment

Is there something I can do to fix this so that I can change the values without the error? Thanks.

Upvotes: 1

Views: 735

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125368

You are creating a list with tuples:

printedrows = [("[X]","[X]","[X]","[X]","[X]","  <- V: {}   TOTAL: {}".format(row.count(0), sum(row))) 
               for row in rows]

You can make those lists instead:

printedrows = [["[X]","[X]","[X]","[X]","[X]","  <- V: {}   TOTAL: {}".format(row.count(0), sum(row))] 
               for row in rows]

Note the square brackets as opposed to the round parenthesis there.

Upvotes: 5

Related Questions