[Tutor] What is the square bracket about?

Dave Kuhlman dkuhlman at rexx.com
Sat Jul 22 19:04:25 CEST 2006


On Sat, Jul 22, 2006 at 08:49:52PM +0800, Ivan Low wrote:
> def adder1(*args):
>      print 'adder1',
>      if type(args[0]) == type(0):
>          sum = 0
> 
>      else:
>          sum = args[0][:0]
>      for arg in args:
>          sum = sum + arg
> 
>      return sum
> 
> Hi, I was trying to understand what this function is all about.
> I didn't tried the adder1 function which result in adding number or  
> text together which I think there is an easier way to do it right?  
> Why go through all the way to write a function like this?
> 
> The square is a big mystery to me. I can't explain why it is there.
> I tried sum(1,2,3) and sum('a','b','c') it wouldn't work. I even  
> search the document and I can't find anything there.
> 

Square brackets are the indexing operator.  When it contains a
colon, it returns a slice, which is a sub-sequence of the sequence
to which it is applied.  See:

    http://docs.python.org/tut/node5.html#SECTION005140000000000000000

In ``args[0][:0]``,

1. args[0] returns the first item in the array args.

2. next, [:0] returns an empty list.  Why?  It returns a slice of
   the list that starts with the first element (because the index
   *before* the colon is omitted) and ends with the element before
   the first element (because of the zero after the colon).

You might try running this code with the pdb debugger.  And, for
example, add code to set a few temporary variables:

    tmp1 = args[0]
    tmp2 = tmp1[:0]

Then, in the debugger, inspect tmp1 and tmp2.

Or, just add a few print statements.

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman


More information about the Tutor mailing list