[Tutor] What is the square brackets about?

Chris Warrick kwpolska at gmail.com
Sat Jan 16 14:02:33 EST 2016


On 16 January 2016 at 16:51, Ege Berkay Gülcan <egeberkay12 at gmail.com> 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]].

loc == [] checks “if `loc` is equal to an empty list”. Note that this
is not a good way to do this. A much better way to spell this would
be:

    if not loc:
        return thing

thing[loc[0]] means “check what the 0th element of `loc` (`loc[0]`)
is, and use it as an index for `thing` (`thing[…]`).

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16


More information about the Tutor mailing list