user3055651
user3055651

Reputation: 13

Index error where I think there isn't

print "Qual deve ser o tamanho do tabuleiro?"
while 1:
    tamanho = input()
    if 1 < tamanho < 6:
        print "Que o jogo comece!"
        break
    else:
        print "Nao posso usar isso como um tabuleiro..."
numeros = tamanho*tamanho-1
x = [range(0,tamanho)]
y = [range(0,tamanho)]
i = 0
while i < tamanho:
    x[i-1] = y[:]
    i = i + 1

I keep getting an index error

IndexError: list assignment index out of range

I am trying to make a matrix with y as the column and x as the row. I tried for loops, while loops... almost everything, can someone help me?
P.S.: I'm still learning, so be patient.

Upvotes: 1

Views: 36

Answers (1)

user2357112
user2357112

Reputation: 280838

x = [range(0,tamanho)]

This makes x a 1-element list whose only element is a tamanho-element list. The y line is similar. That's not what you want. If you want an m-by-n matrix, use an m-by-n nested list:

matrix = [[0]*n for i in xrange(m)]

[0]*n makes an n-element list full of zeros, and the list comprehension makes a list of m of those.

Upvotes: 2

Related Questions