append to non-existing list
Thomas Bellman
bellman at lysator.liu.se
Wed Nov 9 08:54:39 EST 2005
Yves Glodt <y.glodt at sitasoftware.lu> writes:
> I guess that's normal as it's the way python works...?!?
Yes, that's the way Python works.
> My question is: Is there no way to append to a non existing list?
The next time you go shopping at your local super-market, do
*not* get a shopping-cart (or shopping-basket, or any similar
container). As you pick up the things you want to buy, try
to put them into the non-existing cart. Perhaps you will then
become enlightened.
> I am lazy for declaring it first, IMHO it bloats the code, and (don't
> know if it's good to say that here) where I come from (php) I was used
> to not-needing it...
Basically you want Python to automatically create a list out of
nowhere and bind a variable to that list when you try to access
a variable that doesn't exist in a certain way. How do you
propose that Python should now that it is a *list* you want, and
not some other kind of object?
There actually is a way to do what you want:
for row in sqlsth:
try:
pkcolumns.append(row[0].strip())
except NameError:
pkcolumns = [ row[0].strip() ]
However, as you see it is much more work than to do it the right
way. It's also much more fragile; think for example about what
happens if your SQL statement (I assume that's what sqlsth is)
yields zero rows, and you then try to look at pkcolumns after
that loop.
--
Thomas Bellman, Lysator Computer Club, Linköping University, Sweden
"God is real, but Jesus is an integer." ! bellman @ lysator.liu.se
! Make Love -- Nicht Wahr!
More information about the Python-list
mailing list