append to non-existing list

bruno at modulix onurb at xiludom.gro
Wed Nov 9 08:36:25 EST 2005


Yves Glodt wrote:
> Hello,
> 
> if I do this:
> 
> for row in sqlsth:
> ________pkcolumns.append(row[0].strip())
> ________etc
> 
> 
> without a prior:
> 
> pkcolumns = [];
> 
> 
> I get this error on first iteration:
> UnboundLocalError: local variable 'pkcolums' referenced before assignment
> 
> 
> 
> I guess that's normal as it's the way python works...?!?

yes sir.

> My question is: Is there no way to append to a non existing list?

No. Definitively. And that's a Good Thing(tm).

How would you use something that doesn't exist ???

> I am lazy for declaring it first,

s/declaring/instantiating/

If you were to use your own class Toto, would you ever hope that the
following code would work :

for v in some_seq:
  toto.dothis(v)

without instantiating Toto and binding it to the name 'toto' before ?
Well, in Python, a list is an instance of class list. There are
syntactic sugar to instanciate a list (or a tuple or a string or a dict
etc), but this:

my_list = []

is strictly equivalent to this:

my_list = list()

Now let's try something else:

class Machin(object):
  def append(self, value): pass

class Bidule(object):
  def append(self, value): pass

for i in range(10):
  m.append(i)


How should Python interpret this ? Should it create a list, or a Machin,
 or a Bidule, or an instance of whatever imported class having a
append() method ?

> IMHO it bloats the code,

run your python interpreter and type:
import this

Then read carefully.

Now if being explicit still hurts your personal convictions, there's
this other language with a name starting with p... !-)

> and (don't
> know if it's good to say that here) where I come from (php) I was used
> to not-needing it...

Not creating an Array before using it is Bad Style in PHP (and generate
a Warning BTW).

There are warts in Python (as in any other languages), and there are
things that sometimes bore me but are not really warts. But having to
explicitely instanciate objects can't be seen as a wart in any language
IMHO !-)

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list