[Tutor] What is the square brackets about?

Alan Gauld alan.gauld at btinternet.com
Sat Jan 16 14:00:09 EST 2016


On 16/01/16 15:51, Ege Berkay Gülcan wrote:
> def get_(loc, thing):
>     if loc==[]: return thing
>     return get_(loc[1:], thing[loc[0]])
> 
> Hi I am new to Python and I would like to learn about these uses of square
> brackets. I know that loc[1:] means loc list without the first element but
> I do not know the meanings of loc==[] and thing[loc[0]].

[] means an empty list.
so

if loc==[]: return thing

tests whether loc is empty.

Python treats an empty list as being 'false' so the test
could just as easily have been written:

if loc:

thing[loc[0]]

is simply applying an index to thing.

loc[0] returns the value of the first item in loc.
lets assume that is 2

then
thing[loc[0]]
would be the same as
thing[2]

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.

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