[Tutor] <<NEWBIE>> Question re: list.append()
Jeff Shannon
jeff@ccvcorp.com
Mon, 21 Jan 2002 17:17:25 -0800
> "Chris McCormick" <cmccormick@thestate.com> wrote:
>
> I am working on a very small game/AI demo, and I want it to have a
> tile-based map (let me stop here to say that I have scoured the web in vain
> for Python-related tile-based map code/techniques/tutorials, and if you
> have anything related, I would _love_ to get my grubby hands on it).
Have you seen PyGame? (www.pygame.org I believe) I haven't looked at it closely, but I wouldn't be surprised if they have something of this sort there, with a lot of bells and whistles built in...
> map_cells = [ [map.Cell() for j in range(map_cols) ] for i in
> range(map_rows) ]
>
> My first response to this is "That looks disgusting!" I'd probably never
> remember what I was doing. But more to the point, which method is
> faster? My O'Reilly Programming Python says in the footnote on P. 48 that
> L.append(X) is much faster than L+[X]. But the list comprehension is only
> one line, as opposed to several with the for constructs.
Well, first off, a list comprehension is not the same as list addition (the L + [X] mentioned), so the footnote you cite doesn't apply here. Nested list comps *can* look a bit confusing, but they tend to be *slightly* faster than a for-loop. However, you're not likely to notice this speed difference until you start
doing several thousand iterations...
In this case, you're probably best off using whichever method looks clearest to you. Don't worry much about how fast something is, until you've got something running and become aware that it's not fast enough. Keep in mind that you probably won't be creating this map very often, so saving a millisecond or two on its
creation isn't going to affect your game much. :)
Personally, I'd be inclined to take a hybrid approach in this situation:
map_cells = []
for i in range(map_cols):
map_cells.append( [map.Cell() for j in range(map_rows)] )
This uses a list comprehension to create each column, and a for-loop to specify how many columns to build. I personally find this to be the clearest to understand, but of course YMMV.
(I've also reversed your rows and columns, so that you can refer to a given cell by map_cells[x][y]. If you prefer to think in terms of map_cells[row][col], then you can easily reverse them back.)
Jeff Shannon
Technician/Programmer
Credit International