[Tutor] The Python way and two dimensional lists

Alan Gauld alan.gauld at yahoo.co.uk
Mon Nov 22 18:56:34 EST 2021


On 22/11/2021 20:05, Phil wrote:

>> One thing you might consider is using the Python
>> interactive prompt
> 
> I use VS Code for my main projects and IDLE for simple tasks like this 
> one and often, maybe not often enough, use the interactive prompt to 
> test ideas.

When I'm coding a big project I have 3 windows open:
1) The editor or IDE I'm using(depends on language)
2) The interactive interpreter (depends on language)
3) an OS prompt set to run the program (I don't
fully trust IDE tools to run my code, I always do
a final test as an end user would)


In (1) I edit, debug, navigate and version control my code
In (2) I try out ideas, test function operations etc.
       Often copying code snippets from her into the editor.
In (3) I run the "working" code from the IDE. Its amazing
how often new errors or warnings pop up when you run
code outside of the development tools!

Nowadays there will almost certainly be a few web pages
open too...

But if there is an interpreter I'll almost always use it.
Smalltalk programmers have the best implementation of
this way of working. Python's implementation is a close
second IMHO. Lisp programmers are another group who
have traditionally worked this way.

>> Another option that could work here, and is often
>> used in professional code, is to just do the initialisation
>> in a hard coded list format:
> 
> That's the way I had originally set up the grid. I thought I was acting 
> like the big boys by using list comprehension.

comprehensions are fine in some situations, especially
single dimensions or if the initial data is derivable
by formula(eg a constant). But if the data is arbitrary
 - like a Sudoku starting position - then the static
code approach is much easier to read, write and edit.

> I've always found the list comprehension method anything but comprehensible.

They can quickly become incomprehensible, especially when
dealing with multiple dimensions. Splitting the comp into
multiple lines often helps, but somehow seems to go
against the idea of a cmp in the first place....
For example:

solution = [[somefunc(i)
                for i in data
                   if i > limit]
             for n in range(20)]

But then unwinding to regular code looks clearer still:

solution = []
for n in range(20):
    row = []
    for i in data:
       if i > limit: row.append(somefunc(i))

The art is in deciding which approach is most maintainable
and performant(if that's significant, it usually isn't)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list