[TriZPUG] filling lists

Chris Calloway cbc at unc.edu
Tue Apr 7 20:55:13 CEST 2009

On 4/6/2009 6:59 PM, bob gailer wrote:
 > Chris Calloway wrote:
 >> On 4/6/2009 4:18 PM, Joseph Mack NA3T wrote:
 >>> well dang. I didn't see that in the methods and functions for lists.
 >> It's an operator. The subscription operator. Which applies to sequences.
 >> On the left hand side of an assignment, it is only applicable to 
mutable sequences.
 > Not only.

Sorry, I should have added, "if the left hand object is a sequence" to 
be clear.

 > "If the target is a subscription: The primary expression in the 
reference is evaluated. It should yield either a mutable sequence object 
(such as a list) or a mapping object (such as a dictionary)."
 > And even though it does NOT say so, any object with a __setitem__ 
magic method. "Called to implement assignment to |self[key]|. "


The signature for __setitem__ is object.__setitem__(self, key, value):


And that is what backs up:

object[key] = value

for mapping (e.g., dictionary) and mutable sequence objects.

I was trying to distinguish the subscription operator on the left hand 
side of a assignment statement for a mutable sequence from the 
subscription operator's use in an expression, which invokes the 
__getitem__ magic method for both mappings and *all* sequences, both 
mutable and immutable:


That is:

identifier = object[key]


indentifer = object.__getitem__(key)

under the covers (and anywhere object[key] is used as an expression, not 
just on the right hand of an assigment statement).

Joseph, by convention we don't call __setitem__ or __getitem__ directly. 
We use the corresponding operator and Python calls the method for us 
using the method signature. __setitem__ and __getitem__ are a "magic" 
methods that may be overridden for subclasses of list and dict in order 
to customize how the subscription operator works for instances of those 

There are "magic" methods for most (all?) operators. + invokes __add__. 
* invokes __mul__. And so on:


This is how Python implements the object-oriented principle of operator 


There is also an operator module in the Python Standard Library which 
makes these magic methods explicitly callable for those who have special 
functional programming needs:


At the bottom that page is a convenient chart mapping operators to 

Second the recommendation for PIL to deal with pixel data.


Chris Calloway
office: 332 Chapman Hall   phone: (919) 599-3530
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599

More information about the TriZPUG mailing list