List Behavior when inserting new items

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Jan 29 16:44:37 EST 2007


Drew a écrit :
>>What is your actual usecase?
>>
>>diez
> 
> 
> The issue is that I don't know how long the list will eventually be. 

How is this an issue ? Python's lists are not fixed-sized arrays.

> Essentially I'm trying to use a 2D list to hold lines that I will 
> eventually print to the screen.
 >
> Blank elements in the list will be 
> printed as spaces. I suppose every time I add an element, I could find 
> the difference between the size of the list and the desired index and 
> fill in the range between with " " values,

Yes. But note that [1,2,3,' ',' ',4]
is not the same thing as [1,2,3,,,4] (which is not valid Python FWIW).

> however I just wanted to 
> see if there was a more natural way in the language.

I'm not sure I get it. Do you mean you're trying to use a list of lists 
as a representation of a 2D matrix (IOW, a bitmap) ? Something like

bpm = [
   ['X',' ',' ',' ','X'],
   [' ','X',' ','X',' '],
   [' ',' ','X',' ',' '],
   [' ','X',' ','X',' '],
   ['X',' ',' ',' ','X'],
]

If so, using dicts can be somewhat simpler and less memory-consuming:

d = {1:1, 2:2, 3:3}
d[10] = 4
for i in range(1, max(d.keys())+1):
   print d.get(i, ' ')

That is, instead of storing useless spaces for "blank cells" and having 
to do math to compute how many of them you have to insert/delete, you 
just place stuff at desired indices, and 'fill in' spaces when printing 
out to screen.

HTH



More information about the Python-list mailing list