[Tutor] simple list question

Kent Johnson kent37 at tds.net
Tue Feb 21 01:19:41 CET 2006


Ara Kooser wrote:
> Hello all,
> 
>    First off thank you to all the folks that gave input on a smallpox 
> percolation model my students were working on last year. They won first 
> place in the computation division at the science fair and took home the 
> Intel Programming award. I can post or e-mail the code if anyone wants it.
>   
>   This should be simple but I've haven't programmed in python since I 
> started my new job.
> 
>   I am running Python 2.4 on a Windows XP machine (my linux laptop 
> crashed). Editing is done in Idle.
> 
> #
> # Test of a room as list
> # room.py
> #
> 
> room = [' ', ' ', ' ', ' ',
>            '############',
>            '#.................#',
>            '#.................#',
>            '#.................#',
>            '#.................#',
>            '#####.######']
> 
> print room,
> 
> When the program runs my output is this:
>  >>>
> [' ', ' ', ' ', ' ', '############', '#..........#', '#..........#', 
> '############']
> 
> Why is that? I thought that adding , after the print command would allow 
> the format to stay the same. Is there a better way of doing this (I like 
> lists because I can edit them easily)? Thanks.

When you print a list, Python uses a standard format, not the format of 
the source code. For example,

  >>> lst= [ 1,   2,
  ... 3,
  ... 4,5]
  >>> lst
[1, 2, 3, 4, 5]

The original formatting is not preserved.

You can use a loop to print each element on its own line:
  >>> for i in lst:
  ...   print i
  ...
1
2
3
4
5

For anything fancier than that you have to write a fancier (OK, uglier) 
program:

 >>> def printRoom(room):
...   print 'room = [%s,' % ''.join(repr(r)+', ' for r in room[:4])
...   for r in room[4:-1]:
...     print '           ' + repr(r) + ','
...   print '           ' + repr(room[-1] + ']')
...
 >>> printRoom(room)
room = [' ', ' ', ' ', ' ', ,
            '############',
            '#.................#',
            '#.................#',
            '#.................#',
            '#.................#',
            '#####.######]'

But really, what are you trying to do?

Kent



More information about the Tutor mailing list