By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,156 Members | 1,071 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,156 IT Pros & Developers. It's quick & easy.

append to non-existing list

P: n/a
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...?!?

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

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...
regards,
Yves
Nov 9 '05 #1
Share this Question
Share on Google+
25 Replies


P: n/a
Hi

I think there's no way to append to a non existing list.

Sorry about my question, but the English is my second language, and I
don't know what is the meaning of IHMO (or IMHO). I googled and found
that it means "In My Humbled Opinion", is that true? Thanks and accept
my appologies for not talking entirely about your problem.

Daniel

Nov 9 '05 #2

P: n/a
I am afraid you have to either go back to php or whatever programming
language that fits your style or change your style to fit python.

There is a lot I don't like about python but if you have to use it, you
have to cope with it.

Yves Glodt wrote:
My question is: Is there no way to append to a non existing list?

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...
regards,
Yves


Nov 9 '05 #3

P: n/a
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...?!?

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

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...
regards,
Yves


You mean you want to type "pkcolumns" only once to keep your code short?
Would something like this be useful?

pkcolumns = [row.strip() for row in sqlsth]
Nov 9 '05 #4

P: n/a

Juho Schultz wrote:
Yves Glodt wrote:
Hello,

if I do this:

for row in sqlsth:
________pkcolumns.append(row[0].strip())
________etc

You mean you want to type "pkcolumns" only once to keep your code short?
Would something like this be useful?

pkcolumns = [row.strip() for row in sqlsth]


I don't think this is the same as his original code though. There is an
"etc" there. Your version is cleaner and easier to understand but it
can mean another extra pass to go through the result and if sqlsth is
an iterable, it needs to be saved away before iterating it.

Nov 9 '05 #5

P: n/a
bo****@gmail.com wrote:
I am afraid you have to either go back to php or whatever programming
language that fits your style or change your style to fit python.
sorry for offending... I just asked a question, and now I know one more
thing about python...

And btw I really am surprised by the amount of answers that my question
rose, in so little time!

thanks all!
There is a lot I don't like about python but if you have to use it, you
have to cope with it.

Yves Glodt wrote:
My question is: Is there no way to append to a non existing list?

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...
regards,
Yves


Nov 9 '05 #6

P: n/a
Juho Schultz wrote:
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...?!?

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

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...
regards,
Yves


You mean you want to type "pkcolumns" only once to keep your code short?
Would something like this be useful?

pkcolumns = [row.strip() for row in sqlsth]


I will look into this, maybe it's what I need, thanks!
Nov 9 '05 #7

P: n/a
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 'o****@xiludom.gro'.split('@')])"
Nov 9 '05 #8

P: n/a
Yves Glodt <y.*****@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!
Nov 9 '05 #9

P: n/a

Thomas Bellman wrote:
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.


But in PHP(and I believe Perl), it is more like :

"oops, I need a cart. <shout>Hello, I need a cart here, please" and
magically, someone wheel you a cart which you can put your stuff in.
The "@" is the magic calls for service. So as a customer, this sounds
like better service but that will create problems to the super market
as it need extra staff for this service and the environment is noiser,
that is another story.

Nov 9 '05 #10

P: n/a
bruno at modulix wrote:
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 ?


ok I see your point, and python's...

(just FYI, and not to start a flamewar ;-):
In php, the [] means "append to an array object".

If the array does not exist yet, it's created. [] *is* explicit for
arrays, thus for php it's clear what you want.)
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... !-)


no thanks, this is the 21st century ;-)
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).


an "undefined" notice, yes, not a warning... ;-)
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 !-)


Ok... I thank you for all the explanations.

It helps me to see more far. I (and will continue to) use php for web,
and wanna standardize on python for all non-web stuff we are doing, so I
might be a frequent guest on this list...

have a nice day,
Yves
Nov 9 '05 #11

P: n/a
Yves Glodt wrote:
bruno at modulix wrote:
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...?!?

Well you could do something like this. (Untested and unrecommended)

self.__dict__.setdefault('pkcolumns', []).append(row[0].strip())

Personally I find

pkcolumns = []
pkcolumns .append(row[0].strip())

to be nicer ;-)

--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
Nov 9 '05 #12

P: n/a
bo****@gmail.com wrote:
Thomas Bellman wrote:
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.


But in PHP(and I believe Perl), it is more like :

"oops, I need a cart. <shout>Hello, I need a cart here, please" and
magically, someone wheel you a cart which you can put your stuff in.
The "@" is the magic calls for service. So as a customer, this sounds
like better service but that will create problems to the super market
as it need extra staff for this service and the environment is noiser,
that is another story.


:-)

I will never mention any p-language except python in this list anymore...
Nov 9 '05 #13

P: n/a
Max M wrote:
Yves Glodt wrote:
bruno at modulix wrote:
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...?!?

Well you could do something like this. (Untested and unrecommended)

self.__dict__.setdefault('pkcolumns', []).append(row[0].strip())

Personally I find

pkcolumns = []
pkcolumns .append(row[0].strip())

to be nicer ;-)


Yes me too, I'm gonna stick to that... :-)
Nov 9 '05 #14

P: n/a
Yves Glodt <y.*****@sitasoftware.lu> wrote:
My question is: Is there no way to append to a non existing list?
Nope. The problem (well, part of the problem, anyway) is that when you do:

foo.append (bar)

what's happening is you're calling foo's append method. If foo doesn't
already exist, it has no way of knowing what to call.
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...


Python is not php. Nor is it Perl. Nor it is a whole bunch of other
things.
Nov 9 '05 #15

P: n/a
In article <ma**************************************@python.o rg>,
Yves Glodt <y.*****@sitasoftware.lu> wrote:
You mean you want to type "pkcolumns" only once to keep your code short?
Would something like this be useful?

pkcolumns = [row.strip() for row in sqlsth]


I will look into this, maybe it's what I need, thanks!


The list comprehension format described above is handy and compact, and
there's no reason you shouldn't use it when appropriate. That being said,
compactness should not itself be a goal.

Writing clear and easy to understand code is much more important than
reducing the number of lines. Sometimes you get both at the same time, but
not always.
Nov 9 '05 #16

P: n/a
On Wed, 09 Nov 2005 13:46:52 +0100, Yves Glodt wrote:
My question is: Is there no way to append to a non existing list?

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...


But what happens if the non-existent list you try to append to is actually
a non-existent dict, or worse, a non-existent float? You'll get errors and
maybe even crash your computer and wipe the hard disk clear.

*wink*

How is appending to a non-existent object supposed to work?

something.append(0)

What object does the name "something" refer to? Does it even have an
append method? How can you tell what methods it has if it doesn't exist
yet?

No, you can't append to a non-existent list, just as you can't add two
non-existent numbers together.

If PHP allows you to append to non-existent lists, then it is a poor
design decision, and it obviously only works because PHP is much more
limited than Python. Consider the following code:

class PList(list):
def append(self, obj):
print "Appending object to PList"
self.__class__.append(self, obj) # call the superclass

class QList(list):
def append(self, obj):
print "QList append is being called"
self.__class__.append(self, obj)

class RList(QList):
def append(self, obj):
self.__class__.append(self, obj)
print "Now calling RList append"
something.append("hello world") # call append on a non-existent object
What should Python do? Should "something" be a RList, QList, PList or
ordinary list?
--
Steven.

Nov 9 '05 #17

P: n/a
Yves Glodt wrote:
(snip)

ok I see your point, and python's...

(just FYI, and not to start a flamewar ;-):
In php, the [] means "append to an array object".
yes, I know this.
If the array does not exist yet, it's created.
Which is what I don't like. It should crash.
[] *is* explicit for
arrays,
IIRC, you can also use it to sbscript strings, but I wouldn't bet my
life on this.
thus for php it's clear what you want.)
Nope. You may be in the case where you think the array already exists,
and then you (well, I at least...) would prefer that PHP don't try to
second-guess you... If and when I want to create an object, I tell it.
If I dont tell "create me an array", I don't want one to come in existence.

(snip) an "undefined" notice, yes, not a warning... ;-)
(snip)
Ok... I thank you for all the explanations.

It helps me to see more far. I (and will continue to) use php for web,
and wanna standardize on python for all non-web stuff we are doing,
You might discover that Python is just great for web programming too !-)
so I
might be a frequent guest on this list...


You're welcome !-)
And if you're a french speaker, there's also french-speaking mailing
list and newsgroups.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Nov 9 '05 #18

P: n/a
On Wednesday 09 November 2005 07:00, Yves Glodt wrote:

I will never mention any p-language except python in this list anymore...


+1 QOTW

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Nov 9 '05 #19

P: n/a
bruno at modulix wrote:
Yves Glodt wrote:
(snip)
ok I see your point, and python's...

(just FYI, and not to start a flamewar ;-):
In php, the [] means "append to an array object".
yes, I know this.
If the array does not exist yet, it's created.


Which is what I don't like. It should crash.
[] *is* explicit for
arrays,


IIRC, you can also use it to sbscript strings, but I wouldn't bet my
life on this.
thus for php it's clear what you want.)


Nope. You may be in the case where you think the array already exists,
and then you (well, I at least...) would prefer that PHP don't try to
second-guess you... If and when I want to create an object, I tell it.
If I dont tell "create me an array", I don't want one to come in existence.


<not adding fuel to language flamewar>
(snip)
an "undefined" notice, yes, not a warning... ;-)

(snip)
Ok... I thank you for all the explanations.

It helps me to see more far. I (and will continue to) use php for web,
and wanna standardize on python for all non-web stuff we are doing,


You might discover that Python is just great for web programming too !-)


Which raises another question... :-)

Is there a possibility to bring together apache and python in a way that
I can embed python into html?

Or even, write a smallish webserver in python (using twisted maybe)
whose only purpose is to serve pages and execute the embedded code...?

so I
might be a frequent guest on this list...


You're welcome !-)
And if you're a french speaker, there's also french-speaking mailing
list and newsgroups.


Merci pour l'info, I am, but for now the volume of this list is enough
for me ... :-)
Nov 10 '05 #20

P: n/a
Yves Glodt wrote:
Which raises another question... :-)

Is there a possibility to bring together apache and python in a way that
I can embed python into html? What do you mean ?

Or even, write a smallish webserver in python (using twisted maybe)
whose only purpose is to serve pages and execute the embedded code...?

My favorite is TurboGears, a collection of modules and glue that brings
together HTTP server(cherrypy), template(Kid) and SQL object
store(SQLObject) that can do serious web developement yet don't need to
read a book before starting.

If you just need the server, cherrypy is pretty good and simple to
start.

Nov 10 '05 #21

P: n/a
Yves Glodt wrote:
Is there a possibility to bring together apache and python in a way that
I can embed python into html?


http://www.onlamp.com/pub/a/python/2...ver_pages.html
http://www.modpython.org/live/mod_py...html#pyapi-psp

</F>

Nov 10 '05 #22

P: n/a
bo****@gmail.com wrote:
Yves Glodt wrote:
Which raises another question... :-)

Is there a possibility to bring together apache and python in a way that
I can embed python into html?

What do you mean ?


I need this (invalid example-html follows):

<html>
<h1>title of page</h1>

<?py

import time

print "<p>Hello, today is: %s</p>" % (time.ctime())

?>

</html>
Should that not be fairly easy to to, even from scratch, with the
httplib module...?

The advantage would be that I could write a webinterface for my database
and reuse the classes I wrote for the command line app.
Or even, write a smallish webserver in python (using twisted maybe)
whose only purpose is to serve pages and execute the embedded code...?

My favorite is TurboGears, a collection of modules and glue that brings
together HTTP server(cherrypy), template(Kid) and SQL object
store(SQLObject) that can do serious web developement yet don't need to
read a book before starting.

If you just need the server, cherrypy is pretty good and simple to
start.


Ok gonna look into that,

regards,
Yves
Nov 10 '05 #23

P: n/a

Yves Glodt wrote:
I need this (invalid example-html follows):

<html>
<h1>title of page</h1>

<?py

import time

print "<p>Hello, today is: %s</p>" % (time.ctime())

?>

</html>

Cheetah template ?

But I like Kid better as I don't want python in HTML, Kid IMO strikes
the balance between python feature and XHTML so the template is still
readable by any XHTML editors.

Nov 10 '05 #24

P: n/a
On Wed, 09 Nov 2005 20:45:52 +0100, bruno at modulix wrote:
If the array does not exist yet, it's created.


Which is what I don't like. It should crash.


Perhaps not *crash* as such. Raise an exception perhaps.

--
Steven.

Nov 10 '05 #25

P: n/a
Yves Glodt <y.*****@sitasoftware.lu> writes:
Which raises another question... :-)

Is there a possibility to bring together apache and python in a way
that I can embed python into html?
Lots of ways. Most of them aren't really Python, but look a lot like
it.

PSP is most like PHP/ASP/etc., and I believe current mod_python's come
with a PSP processor. Be warned that there's more than one thing
floating around by the name Python Server Pages, and they aren't
completely compatible.

Personally, I prefer Cheetah for this, for three reasons:

1) Cheetah doesn't use X/HTML-like syntax for it's tags, so they don't
interfere with my intelligent X/HTML tools.

2) Cheetah can be used for things other than X/HTML, so you get a
twofer on tools. For my last project, I created the Makefile from a
Cheetah template.

3) Cheetah templates are Classes, so you inherit from them. The same
last project created a top-level template that did the site-wide
banner/nav/etc things, and defined abstracd methods for the
title/content. Pages inherited from that (or in some cases from a
subclass of that) and defined concrete versions of the abstrat
methods. Cheetah templates can inherit from Python classes (which I've
found useful), and Python classes can inherit from Cheetah templates
(which sounds useful, but I haven't used it yet).
Or even, write a smallish webserver in python (using twisted maybe)
whose only purpose is to serve pages and execute the embedded code...?


Well, you could always use the CGIHttpServer module that's in the
standard library for this. Cheetah templates can be tested outside the
sever environment, so you don't need a server to execute the embedded
code.

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Nov 10 '05 #26

This discussion thread is closed

Replies have been disabled for this discussion.