[Tutor] What is the square brackets about?

boB Stepp robertvstepp at gmail.com
Sat Jan 16 14:14:54 EST 2016


On Sat, Jan 16, 2016 at 1:00 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:

> As a side note, this function looks very fragile since
> it depends on thing having nested data structures that
> match the indexes provided by loc.

As Alan's response arrived, I was in the interpreter trying out this
function with a set of values which would enable it to work.  Perhaps
it will illustrate one thing it could do.  It is hard for me to
determine the original intent of the function as the names do not
provide much context.  Perhaps "loc" is short for "location" within
the "thing"?

>>> def get_(loc, thing):
if loc == []: return thing
return get_(loc[1:], thing[loc[0]])

>>> loc = [2]
>>> thing = ['cat', 'dog', 'mouse', 'tick']
>>> get_(loc, thing)
'mouse'

Notice that "thing" appears to work for any "thing" that can be
indexed.  For instance, if I now make "thing" a tuple, the function
will still behave:

>>> thing = ('cat', 'dog', 'mouse', 'tick')
>>> get_(loc, thing)
'mouse'

While learning I find it very helpful to either use IDLE or invoke the
Python interpreter in the shell and try these things out.  Once I get
it to work, then I play around with the syntax and deliberately try to
break things and see what sorts of errors are generated, figure out
the limits of what the syntax will allow, etc., until I feel I am
starting to understand what the original code does.

HTH,

-- 
boB


More information about the Tutor mailing list