jmg87
jmg87

Reputation: 3

appending 2 lists at the same time

I have a function that draws rectangles:

def drawTbl(l, w):

    ln1 = ' '
    ln2 = '-'
    ln3 = '|'

    x = range(l)
    print '+', ln2*w, '+'
    for i in range(len(x)):
        print ln3, ln1*w, ln3
    print '+', ln2*w, '+'

It works fine, but I'm attempting to kind of graph this (this is like a pong clone) so that I can place a ball 'O' at the center and use X and Y for collision detection. When I use this function:

def tblData(l, w):
    table=[]
    for x in range(l):
        table.append([])
    for y in range(w):
        table.append([])

It does seem to append the blank lists, but when I try to use table[x][y], all I receive is an error.

When I return table from tblData, I do get a list of empty lists, but say (l, w) is (12, 56), so I'm trying to place ball 'O' at the center of the grid (6, 28), simply typing table[6][28] returns an error, so I don't know how I would append 'O' to table[6,28]

So my question is, how can I effectively access list[x][y]?

Upvotes: 0

Views: 190

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208665

Instead of creating empty lists you will need to initialize the values in the inner lists to some reasonable value, like a space.

For example:

def tblData(l, w):
    table=[]
    for x in range(l):
        table.append([' '] * w)
    return table

Or more concisely:

def tblData(l, w):
    return [[' '] * w for x in range(l)]

Note that [' '] * 3 creates the list [' ', ' ', ' '], so [' '] * w is equivalent to
[' ' for x in range(w)].

For example:

>>> import pprint
>>> table = [[' '] * 4 for x in range(5)]
>>> pprint.pprint(table)
[[' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' ']]
>>> table[3][1] = 'O'
>>> pprint.pprint(table)
[[' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' '],
 [' ', 'O', ' ', ' '],
 [' ', ' ', ' ', ' ']]

Upvotes: 5

Related Questions