[Tutor] What is the square brackets about?

Alan Gauld alan.gauld at btinternet.com
Sat Jan 16 15:33:12 EST 2016


On 16/01/16 19:35, boB Stepp wrote:

> And so on.  Until you (and I) can understand why the function produces
> these outputs with the given values of loc and thing, then we cannot
> claim we understand what is going on.  So I encourage you to
> thoroughly explore your sample code!

The function plumbs the depths of thing according to the indices
supplies in loc. The shape of thing must match the length of loc.

So if loc = [1,2,3]

thing must be a sequence of sequences of sequences
where the final sequence os at least 4 items long.

That's why I said it was a very fragile function.
Any mismatch in the data is likely to give an
IndexError.

I'd strongly recommend wrapping the second line
in a try/except - at least to aid debugging.

def get_(loc, thing):
    if loc==[]: return thing
    try: return get_(loc[1:], thing[loc[0]])
    except IndexError:
         print "cannot access index", loc[0]," of", thing
         raise

-- 
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