Re: [Tutor] list of dict question

2010-10-12 Thread Francesco Loffredo

On 11/10/2010 19.23, Alan Gauld wrote:

...
HTH,

Sure it did! Very enlightening, Alan. THANK YOU!
Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.862 / Database dei virus: 271.1.1/3190 -  Data di rilascio: 
10/11/10 08:34:00
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dict question

2010-10-11 Thread Alan Gauld


"Francesco Loffredo"  wrote


lst = []
for n in range(3):
obj = {}

I didn't know that this creates a new obj if obj already exists, I
thought it would just update it. That's my mistake.


Yes you have to remember that in Python, unlike C etc,
names are not aliases for memory locations. They are keys
into a namespace dictionary. So the value that the dictionary
refers to can change for any given name - even the type of
object can change.


Does this mean that if I write:
obj = {}
obj = {}
obj = {}
then I'll create 3 different dictionaries, with the name obj 
referring

to the third?


Yes and the first and second will be garbage collected since
there is nothing referring to them now.


obj[n] = str(n)
lst.append(obj)

Creats a list of 3 distinct dictionaries but only uses one name - 
obj.

Ok, this does not lose too much in elegance.


Yes and I could have made it even more elegant with:

lst = []
for n in range(3):
lst.append({n:str(n)})  # no explicit object name needed at all!

And even more tight with:

lst = [ {n:str(n)} for n in range(3)]

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dict question

2010-10-11 Thread Francesco Loffredo
Thank you, Alan and Dave, for your spotting this weak point in my 
understanding of Python!


On 11/10/2010 2.11, Dave Angel wrote:

On 2:59 PM, Alan Gauld wrote:


"Francesco Loffredo"  wrote


did, Roelof's code would work perfectly, and you could store in a list
all the subsequent changes of a dictionary without calling them with
different names.


You don;'t need dfifferent names. Provided the name creates a
new object inside the loop you can reuse the same name.
Roeloff's problem was that he only created one object, outside
his loop.

lst = []
for n in range(3):
obj = {}
I didn't know that this creates a new obj if obj already exists, I 
thought it would just update it. That's my mistake.

Does this mean that if I write:
obj = {}
obj = {}
obj = {}
then I'll create 3 different dictionaries, with the name obj referring 
to the third?



obj[n] = str(n)
lst.append(obj)

Creats a list of 3 distinct dictionaries but only uses one name - obj.

Ok, this does not lose too much in elegance.


I understand that if .append() stored a copy of the dict in the list,
you will end up with lots of copies and a huge amount of memory used by
your list, but that's exactly what will happen if you make those copies
yourself. But you wouldn't have to devise a way to generate a new name
for the dictionary every time you need to update it.


Python uses references throughout, what you are suggesting would
be a change to the normal way that Python uses names.
I needed a hint about what is "the normal way that Python uses names", 
thank you.





Probably more importantly, if a language only implemented copies, you
couldn't have references without some different syntax. On the other
hand, with Python, everything's a reference, and if you want a copy, you
make one when you need it. You never do for immutables, and only you
know when you need it for mutable objects.

DaveA
Thank you too, Dave. I thought that to make a copy you would have to 
create a different name, and this sounded too cumbersome for me...


Francesco
Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.862 / Database dei virus: 271.1.1/3188 -  Data di rilascio: 
10/10/10 08:34:00
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dict question

2010-10-10 Thread Dave Angel

 On 2:59 PM, Alan Gauld wrote:


"Francesco Loffredo"  wrote


did, Roelof's code would work perfectly, and you could store in a list
all the subsequent changes of a dictionary without calling them with
different names.


You don;'t need dfifferent names. Provided the name creates a
new object inside the loop you can reuse the same name.
Roeloff's problem was that he only created one object, outside
his loop.

lst = []
for n in range(3):
obj = {}
obj[n] = str(n)
lst.append(obj)

Creats a list of 3 distinct dictionaries but only uses one name - obj.


I understand that if .append() stored a copy of the dict in the list,
you will end up with lots of copies and a huge amount of memory used by
your list, but that's exactly what will happen if you make those copies
yourself. But you wouldn't have to devise a way to generate a new name
for the dictionary every time you need to update it.


Python uses references throughout, what you are suggesting would
be a change to the normal way that Python uses names.

HTH,

Probably more importantly, if a language only implemented copies, you 
couldn't have references without some different syntax.  On the other 
hand, with Python, everything's a reference, and if you want a copy, you 
make one when you need it.  You never do for immutables, and only you 
know when you need it for mutable objects.


DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dict question

2010-10-10 Thread Alan Gauld


"Francesco Loffredo"  wrote

did, Roelof's code would work perfectly, and you could store in a 
list

all the subsequent changes of a dictionary without calling them with
different names.


You don;'t need dfifferent names. Provided the name creates a
new object inside the loop you can reuse the same name.
Roeloff's problem was that he only created one object, outside
his loop.

lst = []
for n in range(3):
obj = {}
obj[n] = str(n)
lst.append(obj)

Creats a list of 3 distinct dictionaries but only uses one name - obj.

I understand that if .append() stored a copy of the dict in the 
list,
you will end up with lots of copies and a huge amount of memory used 
by
your list, but that's exactly what will happen if you make those 
copies
yourself. But you wouldn't have to devise a way to generate a new 
name

for the dictionary every time you need to update it.


Python uses references throughout, what you are suggesting would
be a change to the normal way that Python uses names.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dict question

2010-10-10 Thread Francesco Loffredo

On 09/10/2010 10.25, Alan Gauld wrote:

"Francesco Loffredo"  wrote


> On the next iteration you overwrite those two dictionaries
> with new values then append them to the list again.
> So you wind up with 2 copies of the updated dictionaries.
> ...
This is difficult for me too: why does this happen? Or, more correctly,
why should this happen?


It happens because you can't store two objects in one.
There is only one dictionary. If you change its value you
change its value.


How can you save the current contents of a dictionary in a list,
making sure that the saved values won't change if you update the dict?


You need to save a copy of the dictionary. ie Create a new dictionary.
If you put a box of white eggs in your shopping basket you cannot put
brown eggs into that box and expect to still have the white ones as well.
You need to get two boxes!
I obviously haven't been clear in my question, sure I know that if you 
change one object you lose the previous contents, but (hope this makes 
my question clear) why should the append method of the list store a 
pointer to the dictionary, rather then a copy of that dictionary? If it 
did, Roelof's code would work perfectly, and you could store in a list 
all the subsequent changes of a dictionary without calling them with 
different names. For example (and this should make my previous example a 
bit fuller), if you had a dictionary containing the current status of a 
system, and you wanted to keep an history of that status (well, I'd use 
a file, but let's imagine you had to use a list), you could simply add 
the (newer version of the) dictionary to the list:



myDictList.append(UpdateIt(myDict))


This would be much more elegant and readable than creating a different 
dictionary (meaning a different name) for every state of the said 
system, and making sure you never repeat a name twice, or you'll lose 
the state you saved some time ago...
I understand that if .append() stored a copy of the dict in the list, 
you will end up with lots of copies and a huge amount of memory used by 
your list, but that's exactly what will happen if you make those copies 
yourself. But you wouldn't have to devise a way to generate a new name 
for the dictionary every time you need to update it.


Thank you for your help
Francesco
Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.862 / Database dei virus: 271.1.1/3186 -  Data di rilascio: 
10/09/10 08:34:00
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dict question

2010-10-09 Thread Alan Gauld

"Francesco Loffredo"  wrote


> On the next iteration you overwrite those two dictionaries
> with new values then append them to the list again.
> So you wind up with 2 copies of the updated dictionaries.
> ...
This is difficult for me too: why does this happen? Or, more 
correctly,

why should this happen?


It happens because you can't store two objects in one.
There is only one dictionary. If you change its value you
change its value.


How can you save the current contents of a dictionary in a list,
making sure that the saved values won't change if you update the 
dict?


You need to save a copy of the dictionary. ie Create a new dictionary.
If you put a box of white eggs in your shopping basket you cannot put
brown eggs into that box and expect to still have the white ones as 
well.

You need to get two boxes!

You tell Roelof that the dictionary must be created at every loop, 
but

if so, where goes the elegance of
myDictList.append(UpdateIt(myDict))


I don't understand what you mean here. What elegance?
Can you give a slightly fuller example?

You can update an existing dictionary in a list, but it doesn't 
preserve

the original vesion any more than replacing white eggs with brown
preserves the white ones.

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dict question

2010-10-09 Thread Francesco Loffredo

On 09/10/2010 9.37, Steven D'Aprano wrote:

On Sat, 9 Oct 2010 06:05:57 pm Francesco Loffredo wrote:

Alan's answer to Roelof made me think...


I'm sorry, I don't know what your question is. You seem to have quoted
various bits and pieces of text from earlier emails (text beginning
with>  signs). Apart from the sentence beginning with "Alan's answer to
Roelof...", and another sentence "This was your answer to Roelof",
everything in your post was a quote (started with a>  sign). So what is
your question about lists of dicts?
Right, I forgot to delete the > signs... I was re-posting a question I 
asked (to Alan) in a previous post (while answering to Roelof). Here is 
my question:


> ...
> On the next iteration you overwrite those two dictionaries
> with new values then append them to the list again.
> So you wind up with 2 copies of the updated dictionaries.
> ...
This is difficult for me too: why does this happen? Or, more correctly,
why should this happen? How can you save the current contents of a
dictionary in a list, making sure that the saved values won't change if
you update the dict?
You tell Roelof that the dictionary must be created at every loop, but
if so, where goes the elegance of
myDictList.append(UpdateIt(myDict))
???

Francesco
Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.862 / Database dei virus: 271.1.1/3184 -  Data di rilascio: 
10/08/10 08:34:00
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dict question

2010-10-09 Thread Steven D'Aprano
On Sat, 9 Oct 2010 06:05:57 pm Francesco Loffredo wrote:
> Alan's answer to Roelof made me think...

I'm sorry, I don't know what your question is. You seem to have quoted 
various bits and pieces of text from earlier emails (text beginning 
with > signs). Apart from the sentence beginning with "Alan's answer to 
Roelof...", and another sentence "This was your answer to Roelof", 
everything in your post was a quote (started with a > sign). So what is 
your question about lists of dicts?



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] list of dict question

2010-10-09 Thread Francesco Loffredo

Alan's answer to Roelof made me think...

On 08/10/2010 13.40, Francesco Loffredo wrote:

Il 08/10/2010 10.02, Alan Gauld ha scritto:


"Roelof Wobben"  wrote


I have this programm :

tournooi = [{'thuis': 'A','uit': "B",'thuisscore': 20, 'uitscore':

...


This was your answer to Roelof:

On the next iteration you overwrite those two dictionaries
with new values then append them to the list again.
So you wind up with 2 copies of the updated dictionaries.
...

This is difficult for me too: why does this happen? Or, more correctly,
why should this happen? How can you save the current contents of a
dictionary in a list, making sure that the saved values won't change if
you update the dict?
You tell Roelof that the dictionary must be created at every loop, but
if so, where goes the elegance of
myDictList.append(UpdateIt(myDict))
???

Francesco (puzzled)
Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.862 / Database dei virus: 271.1.1/3184 -  Data di rilascio: 
10/08/10 08:34:00
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dict question

2010-10-08 Thread Francesco Loffredo

Il 08/10/2010 10.02, Alan Gauld ha scritto:


"Roelof Wobben"  wrote


I have this programm :

tournooi = [{'thuis': 'A','uit': "B",'thuisscore': 20, 'uitscore':

...

for wedstrijd in tournooi :
if wedstrijd['thuis'] in stand :
print "True"


stand is a list of dictionaries so this will never be True.
...

if wedstrijd['uit'] in stand :
print "True"


But stand is a list with a dictionary inside so this test
cannot be true since wedstrijg['uit'] is not a dictionary.

I'll say the same another way: you are searching an apple in a container 
of baskets, one of which MAY CONTAIN an apple. But you only see baskets, 
and none of those can BE an apple!
My two cents: the following might be still new for you, but this is a 
way to check if wedstrijd['thuis'] is in stand:


if wedstrijd['thuis'] in [u['ploeg'] for u in stand]

where you build a temporary list of 'ploeg's in stand and check whether 
wedstrijd['thuis'] is found there.



...
On the next iteration you overwrite those two dictionaries
with new values then append them to the list again.
So you wind up with 2 copies of the updated dictionaries.
...
This is difficult for me too: why does this happen? Or, more correctly, 
why should this happen? How can you save the current contents of a 
dictionary in a list, making sure that the saved values won't change if 
you update the dict?
You tell Roelof that the dictionary must be created at every loop, but 
if so, where goes the elegance of

myDictList.append(UpdateIt(myDict))
???

Francesco (puzzled)
Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.862 / Database dei virus: 271.1.1/3182 -  Data di rilascio: 
10/07/10 08:34:00
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dict question

2010-10-08 Thread Roelof Wobben




> To: tutor@python.org
> From: alan.ga...@btinternet.com
> Date: Fri, 8 Oct 2010 09:02:05 +0100
> Subject: Re: [Tutor] list of dict question
>
>
> "Roelof Wobben" wrote
>
>> I have this programm :
>>
>> tournooi = [{'thuis': 'A','uit': "B",'thuisscore': 20, 'uitscore':
>> 15},{'thuis': 'C','uit': "D",'thuisscore': 80, 'uitscore': 40}]
>> stand = []
>> tussen_thuis = {}
>> tussen_uit = {}
>
> Here you create your dictionary objects.
> You never create any more dictionary objects so these are the only
> ones you have.
>
>> for wedstrijd in tournooi :
>> if wedstrijd['thuis'] in stand :
>> print "True"
>
> stand is a list of dictionaries so this will never be True.
>
>> else :
>> tussen_thuis['ploeg'] = wedstrijd['thuis']
>> tussen_thuis['wedstrijden'] = 1
>> if wedstrijd['thuisscore']> wedstrijd['uitscore']:
>> tussen_thuis['punten'] = 2
>> else:
>> tussen_thuis['punten'] = 0
>>
>> tussen_thuis['voor'] = wedstrijd['thuisscore']
>> tussen_thuis ['tegen'] = wedstrijd['uitscore']
>> stand.append(tussen_thuis)
>
> Here you append the dictionary into stand
>
>> if wedstrijd['uit'] in stand :
>> print "True"
>
> But stand is a list with a dictionary inside so this test
> cannot be true since wedstrijg['uit'] is not a dictionary.
>
>> else :
>> tussen_uit['ploeg'] = wedstrijd['uit']
>> tussen_uit['wedstrijden'] = 1
>> if wedstrijd['thuisscore'] < wedstrijd['uitscore']:
>> tussen_uit['punten'] = 2
>> else:
>> tussen_uit['punten'] = 0
>> tussen_uit['tegen'] = wedstrijd['thuisscore']
>> tussen_uit ['voor'] = wedstrijd['uitscore']
>> stand.append(tussen_uit)
>
> Now you append a second dictionary to stand.
>
> On the next iteration you overwrite those two dictionaries
> with new values then append them to the list again.
> So you wind up with 2 copies of the updated dictionaries.
>
>> So the data of A and B are overwriting by C and D.
>> How can I prevent this ?
>
> You need to create new dictionaries for each iteration of the loop.
> Move the dictionary creation lines inside the loop.
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

 
Hello Alan, 
 
Thank you.
Now i can work on a script which can check if a team exist in standen.
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dict question

2010-10-08 Thread Alan Gauld


"Roelof Wobben"  wrote


I have this programm :

tournooi = [{'thuis': 'A','uit': "B",'thuisscore': 20, 'uitscore': 
15},{'thuis': 'C','uit': "D",'thuisscore': 80, 'uitscore': 40}]

stand = []
tussen_thuis = {}
tussen_uit = {}


Here you create your dictionary objects.
You never create any more dictionary objects so these are the only 
ones you have.



for wedstrijd in tournooi :
   if wedstrijd['thuis'] in stand :
   print "True"


stand is a list of dictionaries so this will never be True.


   else :
   tussen_thuis['ploeg']  = wedstrijd['thuis']
   tussen_thuis['wedstrijden'] = 1
   if wedstrijd['thuisscore']> wedstrijd['uitscore']:
   tussen_thuis['punten'] = 2
   else:
   tussen_thuis['punten'] = 0

   tussen_thuis['voor'] = wedstrijd['thuisscore']
   tussen_thuis ['tegen'] = wedstrijd['uitscore']
   stand.append(tussen_thuis)


Here you append the dictionary into stand


   if wedstrijd['uit'] in stand :
   print "True"


But stand is a list with a dictionary inside so this test
cannot be true since wedstrijg['uit'] is not a dictionary.


   else :
   tussen_uit['ploeg']  = wedstrijd['uit']
   tussen_uit['wedstrijden'] = 1
   if wedstrijd['thuisscore'] < wedstrijd['uitscore']:
   tussen_uit['punten'] = 2
   else:
   tussen_uit['punten'] = 0
   tussen_uit['tegen'] = wedstrijd['thuisscore']
   tussen_uit ['voor'] = wedstrijd['uitscore']
   stand.append(tussen_uit)


Now you append a second dictionary to stand.

On the next iteration you overwrite those two dictionaries
with new values then append them to the list again.
So you wind up with 2 copies of the updated dictionaries.


So the data of A and B are overwriting by C and D.
How can I prevent this ?


You need to create new dictionaries for each iteration of the loop.
Move the dictionary creation lines inside the loop.

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] list of dict question

2010-10-08 Thread Roelof Wobben


Hello, 
 
I have this programm :
 
tournooi = [{'thuis': 'A','uit': "B",'thuisscore': 20, 'uitscore': 
15},{'thuis': 'C','uit': "D",'thuisscore': 80, 'uitscore': 40}]
stand = []
tussen_thuis = {}
tussen_uit = {}
for wedstrijd in tournooi :
if wedstrijd['thuis'] in stand :
print "True"
else :
tussen_thuis['ploeg']  = wedstrijd['thuis']
tussen_thuis['wedstrijden'] = 1
if wedstrijd['thuisscore']> wedstrijd['uitscore']:
tussen_thuis['punten'] = 2
else:
tussen_thuis['punten'] = 0 

tussen_thuis['voor'] = wedstrijd['thuisscore']
tussen_thuis ['tegen'] = wedstrijd['uitscore']
stand.append(tussen_thuis)
if wedstrijd['uit'] in stand :
print "True"
else :
tussen_uit['ploeg']  = wedstrijd['uit']
tussen_uit['wedstrijden'] = 1
if wedstrijd['thuisscore'] < wedstrijd['uitscore']:
tussen_uit['punten'] = 2
else:
tussen_uit['punten'] = 0 
tussen_uit['tegen'] = wedstrijd['thuisscore']
tussen_uit ['voor'] = wedstrijd['uitscore']
stand.append(tussen_uit)
 
It gives this output :
 
[{'punten': 2, 'tegen': 40, 'wedstrijden': 1, 'voor': 80, 'ploeg': 'C'}, 
{'punten': 0, 'tegen': 80, 'wedstrijden': 1, 'voor': 40, 'ploeg': 'D'}, 
{'punten': 2, 'tegen': 40, 'wedstrijden': 1, 'voor': 80, 'ploeg': 'C'}, 
{'punten': 0, 'tegen': 80, 'wedstrijden': 1, 'voor': 40, 'ploeg': 'D'}]

 
So the data of A and B are overwriting by C and D.
How can I prevent this ?
 
Roelof
 
 
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list comprehension, efficiency?

2010-10-03 Thread bob gailer

 On 10/2/2010 8:02 PM, Steven D'Aprano wrote:

On Sun, 3 Oct 2010 01:17:39 am bob gailer wrote:


I ran dis on a for loop and the equivalent comprehension.

I was surprised to see almost identical code.

I had assumed (and now wish for) that a comprehension would be a
primitive written in C and thus much faster!

How could it be? A list comp is syntactic sugar. It needs to perform the
same steps as a for-loop, and call an arbitrary Python expression. It's
not like map() that takes a function object. Unless you had a separate
primitive for every imaginable Python expression -- which is
impossible -- list comps need to generate relatively similar code to
for-loops because they do relatively similar things.


Thank you. I needed that!

Besides, in recent versions of Python the speed of for-loops is quite
good. The bottleneck is rarely the loop itself, but the work you do in
the loop or the size of the loop.


--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list comprehension, efficiency?

2010-10-02 Thread Steven D'Aprano
On Sun, 3 Oct 2010 01:17:39 am bob gailer wrote:

> I ran dis on a for loop and the equivalent comprehension.
>
> I was surprised to see almost identical code.
>
> I had assumed (and now wish for) that a comprehension would be a
> primitive written in C and thus much faster!

How could it be? A list comp is syntactic sugar. It needs to perform the 
same steps as a for-loop, and call an arbitrary Python expression. It's 
not like map() that takes a function object. Unless you had a separate 
primitive for every imaginable Python expression -- which is 
impossible -- list comps need to generate relatively similar code to 
for-loops because they do relatively similar things.

Besides, in recent versions of Python the speed of for-loops is quite 
good. The bottleneck is rarely the loop itself, but the work you do in 
the loop or the size of the loop.


-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list comprehension, efficiency?

2010-10-02 Thread bob gailer

 [snip]

I ran dis on a for loop and the equivalent comprehension.

I was surprised to see almost identical code.

I had assumed (and now wish for) that a comprehension would be a 
primitive written in C and thus much faster!


--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list comprehension, efficiency?

2010-09-28 Thread Bill Campbell
On Tue, Sep 28, 2010, Lie Ryan wrote:
>On 09/28/10 13:57, Bill Allen wrote:
>> I can now see that quite a bit of the code I write dealing with lists
>> can be done with list
>> comprehensions.   My question is this, is the list comprehension styled
>> code generally
>> more efficient at runtime?  If so, why?
>
>Yes, because the looping in list comprehension is done in C instead of a
>python construct. However, they are the type of efficiency that you
>shouldn't bother yourself with unless you're microoptimizing.

True enough, but dealing with large lists can be expensive,
particularly when appending.  Before I discovered sets, I found
significant time savings by creating a dictionary, adding as
necessary, then use d.keys() to get the keys back.

This became a significant factor when I was selecting unique
lines from about 1.3 million samples.

Bill
-- 
INTERNET:   b...@celestial.com  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
Voice:  (206) 236-1676  Mercer Island, WA 98040-0820
Fax:(206) 232-9186  Skype: jwccsllc (206) 855-5792

Independent self-reliant people would be a counterproductive anachronism
in the collective society of the future where people will be defined by
their associations.  1896 John Dewey, educational philosopher, proponent
of modern public schools.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list comprehension, efficiency?

2010-09-28 Thread Steven D'Aprano
On Tue, 28 Sep 2010 01:57:23 pm Bill Allen wrote:

> I can now see that quite a bit of the code I write dealing with lists
> can be done with list
> comprehensions.   My question is this, is the list comprehension
> styled code generally
> more efficient at runtime?  If so, why?


List comprehensions *are* lists, or rather, they produce lists.

A list comprehension 

result = [expr for x in seq] 

is just syntactic sugar for a for-loop:

result = []
for x in seq:
result.append(x)

except that in Python 3, the "x" variable is hidden. (In Python 2 it is 
not, but that was an accident.) The end result is exactly the same 
whether you use a list comp or a for-loop.

The advantage of for-loops is that you can do much more complex code. 
That complexity comes at a cost, and consequently for-loops tend to be 
a little bit slower than list comprehensions: some of the work can be 
done under the hood, faster than regular Python code. But for most 
cases, this difference is relatively small and won't make any real 
difference. What does it matter if your program runs in 24 milliseconds 
instead of 22 milliseconds? Or five hours and seventeen minutes instead 
of five hours and sixteen minutes? Who cares? Write the code that is 
most natural and easy to read and understand, and only worry about such 
tiny savings when you absolutely have to.

But there is one case where for-loops are potentially MUCH faster than 
list comps. List comps always run all the way to the end, but for-loops 
can break out early. If your problem lets you break out of the loop 
early, this is a good thing. So this for-loop:


for x in xrange(1000):
result.append(x+1)
if x > 5: break


will beat the pants off this list comp:

[x+1 for x in xrange(1000) if x <= 5]

There's no way to break out of the list comp early -- it has to keep 
going past 5 all the way to the end.


-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list comprehension, efficiency?

2010-09-27 Thread Lie Ryan
On 09/28/10 13:57, Bill Allen wrote:
> I can now see that quite a bit of the code I write dealing with lists
> can be done with list
> comprehensions.   My question is this, is the list comprehension styled
> code generally
> more efficient at runtime?  If so, why?

Yes, because the looping in list comprehension is done in C instead of a
python construct. However, they are the type of efficiency that you
shouldn't bother yourself with unless you're microoptimizing.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] list comprehension, efficiency?

2010-09-27 Thread Bill Allen
I have seen list comprehensions used, but have not quite got the hang of it
yet.
So, I was writing a bit of code to do some work with file directories and
decided
to give it a try as follows:

list_c = os.listdir("c:")

#first code written in the way I usually would.
dirs = []
for x in list_c:
if os.path.isdir(x):
dirs.append(x)

#replaced the above code with the following list comprehension, it worked as
expected:
dirs = [x for x in list_c if os.path.isdir(x)]

I can now see that quite a bit of the code I write dealing with lists can be
done with list
comprehensions.   My question is this, is the list comprehension styled code
generally
more efficient at runtime?  If so, why?

--Bill
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list dll functions?

2010-09-15 Thread ALAN GAULD
Find the Pythonwin IDE executable and run it - its a better IDE than IDLE in my 
opinion, especially if you are on Windows.

Once it is started you can go to the Tools->COM Browser menu item and 
it starts an explorer type Window. The top level "folders" are:

Registered Objects
Running Objects
Registered Type Libraries

You can then drill down and explore as you wish.
For example under Registered Type Libraries there is Accessibility.
Within that there is TypeLibrary-> IAccessible-Dispatch
Within that there are functions such as  AddRef, Invoke, GetTypeInfo etc.

Inside those you can see the parameters etc.


Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/




- Original Message 
> From: Alex Hall 
> To: Alan Gauld 
> Sent: Wednesday, 15 September, 2010 15:57:43
> Subject: Re: [Tutor] list dll functions?
> 
> On 9/15/10, Alan Gauld   wrote:
> >
> > "Alex Hall"   wrote
> >
> >> Out of curiosity: I know I can call dll functions from  python using
> >> the win32 lib, but is there any way to simply "examine"  a loaded dll
> >> to see all of the functions and attributes it exposes  for use?
> >
> > There are various tools around to do that and hopefully  some
> > documentation!
> >
> > But often nowadays DLLs expose a COM  object model and
> > you have a COM browser built into Pythonwin. That will  give
> > you a windows explorer type view of the objects and their
> >  operations.
> How would you go about doing that? I have the pywin  extension
> installed for my python installation.
> >
> > If the DLL is  purely perocedural then that won't help.
> >
> >  HTH,
> >
> >
> > --
> > Alan Gauld
> > Author of the Learn  to Program web site
> > http://www.alan-g.me.uk/
> >
> >
> >  ___
> > Tutor maillist   -  Tutor@python.org
> > To unsubscribe or  change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> >
> 
> 
> -- 
> Have a great day,
> Alex (msg sent from GMail website)
> mehg...@gmail.com; http://www.facebook.com/mehgcap
> 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list dll functions?

2010-09-15 Thread Alan Gauld


"Alex Hall"  wrote


Out of curiosity: I know I can call dll functions from python using
the win32 lib, but is there any way to simply "examine" a loaded dll
to see all of the functions and attributes it exposes for use?


There are various tools around to do that and hopefully some
documentation!

But often nowadays DLLs expose a COM object model and
you have a COM browser built into Pythonwin. That will give
you a windows explorer type view of the objects and their
operations.

If the DLL is purely perocedural then that won't help.

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list dll functions ?

2010-09-15 Thread patrice laporte
Dependdencyy walker is a good tool, but as you have seen it doesn't give you
function's signature. If you explore a MS dll, you should to have a look at
MSDN and read about the function description.

A bit out of subject : There is no way to find the function's signature only
from exploring the binary file (I never found one at least). Following
article explain the MS PE (Portable Executable, no elf format in Windows),
but it doesn't explain more about signature. this is why you need headers
and lib file to link a w32 app.

http://msdn.microsoft.com/en-us/library/ms809762.aspx
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list dll functions?

2010-09-14 Thread Alex Hall
On 9/14/10, R. Alan Monroe  wrote:
>> the win32 lib, but is there any way to simply "examine" a loaded dll
>> to see all of the functions and attributes it exposes for use? I would
>
> http://www.dependencywalker.com/
A great program, thanks! Best of all, for me anyway, it works well (so
far) with JAWS, my screen reader. It is increasingly rare to find
fully accessible programs nowadays, and I am glad that this one works.
Now I just have to figure out how to see the expected arguments of a
function, but I am sure that is in the manual somewhere...
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list dll functions?

2010-09-14 Thread R. Alan Monroe
> the win32 lib, but is there any way to simply "examine" a loaded dll
> to see all of the functions and attributes it exposes for use? I would

http://www.dependencywalker.com/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] list dll functions?

2010-09-14 Thread Alex Hall
Hi all,
Out of curiosity: I know I can call dll functions from python using
the win32 lib, but is there any way to simply "examine" a loaded dll
to see all of the functions and attributes it exposes for use? I would
do no good with a hex editor since I have no idea what all the numbers
mean, so I am hoping for a plaintext representation of a dll's
possibilities and am most comfortable in Python. I am running the
latest 2.6 on win7. TIA.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list index out of range

2010-09-14 Thread Francesco Loffredo

My humble guess: (sure, the full traceback would help A LOT!)

On 09/09/2010 23.52, Todd Ballard wrote:

y=[daily_solar_radiation["MJ"][0]]
for i in xrange(0,275):
 y=[daily_solar_radiation["MJ"]][i]+y[i-1] # <--THIS y[i-1] is out of 
bounds when i=0 !!!


Hope that helps

Francesco
Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.851 / Database dei virus: 271.1.1/3132 -  Data di rilascio: 
09/13/10 08:35:00
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list index out of range

2010-09-12 Thread Steven D'Aprano
On Fri, 10 Sep 2010 07:52:20 am Todd Ballard wrote:
> I am attempting to have a cummalative total of the y values and
> receive a "list index out of range" error message

How unfortunate.

Do you have an actual question to ask, or are you just sharing?

If you are having problems fixing the error, what does the stack 
traceback say? Not just the error message, which is the least important 
part of the error, but the entire traceback. This will show *where* the 
function occurs, as well as *what* the error is, and sometimes *why* as 
well.


A couple of other comments follow:

> import filereader
> from filereader import *

It's rare to actually need to do both of this together. Are you sure you 
need both? It's generally better to stick to the first form, and have 
fully-qualified names like filereader.read_array. If that's too long, 
it's best to import only the functions you actually need, which in your 
case seems to be:

from filereader import read_array

The "import *" form should be considered advanced usage best avoided 
unless you know what you're doing.

> My_Path="C:\\Python26\\assignment2\\datadownload.txt"

A little-known fact: Windows supports both \ and / as the directory 
separator. Since Python uses backslash for the escape character, it 
gets tedious and error-prone to write strings with lots of backslashes. 
So the best way to write pathnames under Windows in Python is with 
forward-slashes:

My_Path="C:/Python26/assignment2/datadownload.txt"


> y=[]
> for i in xrange(0,365):

There's no need to say xrange(0, 365). Just xrange(365) will have the 
same effect, because the starting index defaults to 0.

> y+=[daily_solar_radiation["MJ"][i]]

It's generally more efficient to use:

y.append(daily_solar_radiation["MJ"][i])

instead of y += [...] as you do, although for only 365 items it won't 
make a huge difference.


> from filereader import *

You've already done this above, you don't need to do this again.





-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] list index out of range

2010-09-12 Thread Todd Ballard
I am attempting to have a cummalative total of the y values and receive a "list 
index out of range" error message

import numpy
import matplotlib.pyplot as plt

import filereader
from filereader import *

My_Path="C:\\Python26\\assignment2\\datadownload.txt"
My_Data_Type=numpy.dtype([("year","int32"),("day","int32"),("MJ","float64")])
daily_solar_radiation=read_array(My_Path,My_Data_Type,separator=None)

y=[]
for i in xrange(0,365):
y+=[daily_solar_radiation["MJ"][i]]

x=[]
for i in xrange(0,365):
x+=[daily_solar_radiation["day"][i]]

plt.plot(x,y)
plt.title('Daily Radiation')
plt.xlabel('day of the year')
plt.ylabel('MJ/m**2')
plt.show()
plt.savefig('plot1.png')

from filereader import *

My_Path="C:\\Python26\\assignment2\\datadownload.txt"
My_Data_Type=numpy.dtype([("year","int32"),("day","int32"),("MJ","float64")])
daily_solar_radiation=read_array(My_Path,My_Data_Type,skip=91,separator=None)

y=[daily_solar_radiation["MJ"][0]]
for i in xrange(0,275):
y=[daily_solar_radiation["MJ"]][i]+y[i-1]

for i in xrange(0,275):
x+=[daily_solar_radiation["day"][i]]

plt.plot(x,y)
plt.title('Daily Radiation')
plt.xlabel('day of the year')
plt.ylabel('MJ/m**2')
plt.show()
plt.savefig('plot2.png')

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension for dicts?

2010-08-20 Thread Steven D'Aprano
On Sat, 21 Aug 2010 01:47:12 am bob gailer wrote:

> > Well yes, but I pointed out that you *can* bail out early of
> > for-loops, but not list comprehensions. The whole point is with a
> > list comp, you're forced to iterate over the entire sequence, even
> > if you know that you're done and would like to exit.
>
> Take a look at itertools.takewhile!
>
> result = [i%2 for i in itertools.takewhile(lamda x:i<  10, seq)]

Which is an excellent solution to the problem, and I had forgotten about 
it, but takewhile doesn't magically cause the list comprehension to 
exit. The list comp still runs over the entire input list, it's just 
that it sees a smaller input list.

takewhile replaces the input sequence with a new sequence that stops at 
a certain point, so you could write:

result = []
for i in itertools.takewhile(lambda x:i<10, seq):
result.append(i)

as well.

Next time some Perl hacker accuses Python of being "Only one way to do 
it", you can just laugh at them :)



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension for dicts?

2010-08-20 Thread Nitin Das
result = [i%2 for i in itertools.takewhile(lamda x:i<  10, seq)]
is a good approach but it is taking little more time than the for loop over
iterator.

def takewhile(predicate, iterable):
# takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
for x in iterable:
if predicate(x):
yield x
else:
break

I don't know why? As it seems that this for loop and the other for loop
doing the same thing.

--nitin


On Fri, Aug 20, 2010 at 9:17 PM, bob gailer  wrote:

>  On 8/20/2010 5:44 AM, Steven D'Aprano wrote:
>
>> On Fri, 20 Aug 2010 06:10:59 pm Alan Gauld wrote:
>>
>>> "Steven D'Aprano"  wrote
>>>
>>>  the purpose). No matter how fast you can perform a loop, it's
 always faster to avoid it altogether, so this:

 seq = xrange(1000)
 result = []
 for i in seq:
if i>= 10: break
result.append(i%2)


 will be much faster than this:

 seq = xrange(1000)
 result = [i%2 for i in seq if i<  10]

>>> Although it should be pointed out that these are doing very different
>>> things.
>>>
>> Well yes, but I pointed out that you *can* bail out early of for-loops,
>> but not list comprehensions. The whole point is with a list comp,
>> you're forced to iterate over the entire sequence, even if you know
>> that you're done and would like to exit.
>>
>>  Take a look at itertools.takewhile!
>
> result = [i%2 for i in itertools.takewhile(lamda x:i<  10, seq)]
>
>
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension for dicts?

2010-08-20 Thread bob gailer

 On 8/20/2010 5:44 AM, Steven D'Aprano wrote:

On Fri, 20 Aug 2010 06:10:59 pm Alan Gauld wrote:

"Steven D'Aprano"  wrote


the purpose). No matter how fast you can perform a loop, it's
always faster to avoid it altogether, so this:

seq = xrange(1000)
result = []
for i in seq:
if i>= 10: break
result.append(i%2)


will be much faster than this:

seq = xrange(1000)
result = [i%2 for i in seq if i<  10]

Although it should be pointed out that these are doing very different
things.

Well yes, but I pointed out that you *can* bail out early of for-loops,
but not list comprehensions. The whole point is with a list comp,
you're forced to iterate over the entire sequence, even if you know
that you're done and would like to exit.


Take a look at itertools.takewhile!

result = [i%2 for i in itertools.takewhile(lamda x:i<  10, seq)]


--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension for dicts?

2010-08-20 Thread Steven D'Aprano
On Fri, 20 Aug 2010 06:10:59 pm Alan Gauld wrote:
> "Steven D'Aprano"  wrote
>
> > the purpose). No matter how fast you can perform a loop, it's
> > always faster to avoid it altogether, so this:
> >
> > seq = xrange(1000)
> > result = []
> > for i in seq:
> >if i >= 10: break
> >result.append(i%2)
> >
> >
> > will be much faster than this:
> >
> > seq = xrange(1000)
> > result = [i%2 for i in seq if i < 10]
>
> Although it should be pointed out that these are doing very different
> things.

Well yes, but I pointed out that you *can* bail out early of for-loops, 
but not list comprehensions. The whole point is with a list comp, 
you're forced to iterate over the entire sequence, even if you know 
that you're done and would like to exit.



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension for dicts?

2010-08-20 Thread Alan Gauld

"Steven D'Aprano"  wrote


the purpose). No matter how fast you can perform a loop, it's always
faster to avoid it altogether, so this:

seq = xrange(1000)
result = []
for i in seq:
   if i >= 10: break
   result.append(i%2)


will be much faster than this:

seq = xrange(1000)
result = [i%2 for i in seq if i < 10]


Although it should be pointed out that these are doing very different 
things.

The equivalent loop would use continue rather than break, in which
case the LC might be faster. But where you do only want to partially
process a list the explicit loop is the best solution for now.


I've always wanted an until clause in the LC structure:

result = [i%2 for i in seq until i>10]



--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Steven D'Aprano
On Fri, 20 Aug 2010 09:51:08 am Pete wrote:

[...]
> Ah, so list comprehensions are a purely syntactic construct?

No, I don't think that's what Emile was trying to say. It's not like 
list comps are macros that are expanded into the explicit for-loop like 
that. All he is saying is that both the for-loop and the list 
comprehension loop over the list.

There are some functional differences: for example, the list comp avoids 
needing to look up result.append over and over again. Because it knows 
it is dealing with a list, rather than some arbitrary object that 
conceivably might have some weird append method with strange 
side-effects, it can take optimizing short-cuts that aren't applicable 
to general for-loops. 


> I had the feeling there might be a performance benefit of some kind.

If you write the for-loop in the most straight forward, obvious fashion, 
then there is a small but measurable performance cost from repeatedly 
looking up the append method. On the other hand, for-loops are more 
general -- you can call break to exit early, or continue to skip an 
iteration, so they're easier to optimize. There's no way to break out 
of a list comp early (other than raising an exception, which defeats 
the purpose). No matter how fast you can perform a loop, it's always 
faster to avoid it altogether, so this:

seq = xrange(1000)
result = []
for i in seq:
if i >= 10: break
result.append(i%2)


will be much faster than this:

seq = xrange(1000)
result = [i%2 for i in seq if i < 10]


Other than that, the speed of the loop itself is virtually the same as 
the speed of the list comprehension.



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Pete
On 2010-08-19, at 5:25 PM, Emile van Sebille wrote:

> On 8/19/2010 7:51 AM Pete said...
>> Hi,
>> 
>> I've been reading up on list comprehensions lately, all userful and powerful 
>> stuff - trying to wrap my brain around it :)
>> 
>> As the examples all seem to relate to lists, I was wondering if there is an 
>> elegant similar way to apply a function to all keys in a dictionary?
>> 
>> (without looping over it, of course)
> 
> Just fyi, as it sounds you may not understand.  List Comprehensions loop over 
> the list.  There's no other magic going on that avoids that.
> 
> result = [ ii for ii in lst if cond ]
> 
> is just shorthand for
> 
> result = []
> for ii in lst:
>  if cond:
>result.append(ii)
> 
> Emile

Ah, so list comprehensions are a purely syntactic construct?

I had the feeling there might be a performance benefit of some kind.

thanks for all the contributions on this topic, it's been greatly helpful to my 
understanding.

-Pete
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Emile van Sebille

On 8/19/2010 7:51 AM Pete said...

Hi,

I've been reading up on list comprehensions lately, all userful and powerful 
stuff - trying to wrap my brain around it :)

As the examples all seem to relate to lists, I was wondering if there is an 
elegant similar way to apply a function to all keys in a dictionary?

(without looping over it, of course)


Just fyi, as it sounds you may not understand.  List Comprehensions loop 
over the list.  There's no other magic going on that avoids that.


result = [ ii for ii in lst if cond ]

is just shorthand for

result = []
for ii in lst:
  if cond:
result.append(ii)

Emile


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Dave Angel

(You top-posted, so now I have to delete the older part)

Vince Spicer wrote:

Hey you can use list comprehension here

age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 }

you can create a dict from a list of tuples and you can access the dict as
a
list of tuples by accessing its items

Example:

age_dict = dict([(key.upper(), value) for key,value in age_dict.items()])

hope that helps,

Vince

  
The only catch to that is that two or more of the keys may map to the 
same uppercase key.  If one needs to detect that, one has to write an 
explicit loop, rather than just converting with dict()


DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Steven D'Aprano
On Fri, 20 Aug 2010 01:40:54 am Wayne Werner wrote:

> > age_dict = dict([(key.upper(), value) for key,value in
> > age_dict.items()])
>
> This is a bad place to use a list comprehension. This will create a
> list of values first and then create a dict from that list, so now
> you have a list floating around that you didn't need.

How do you know that dict() doesn't need it the entire list at once? 
Unless you're an expert on the implementation, for all you know it 
looks something like this:

class dict:
def __new__(cls, arg):
...
try:
n = len(arg)
except AttributeError:
# probably a generator expression
arg = list(arg)
n = len(arg)
allocate_memory_for_items(n)
...

(only written in C). I'm not saying it does, or that it doesn't, but 
you're assuming a pattern of behaviour which might not be the case.

Here's a similarly common idiom: which of these is faster?

' '.join(gen_expr)
' '.join(list_comp)


[st...@sylar ~]$ python -m timeit "' '.join(str(n) for n in 
xrange(30))"
10 loops, best of 3: 437 msec per loop
[st...@sylar ~]$ python -m timeit "' '.join([str(n) for n in 
xrange(30)])"
10 loops, best of 3: 401 msec per loop

The list comprehension is consistently faster, because join() works more 
efficiently if it knows how many items it needs to pre-allocate memory 
for.


> Generator expressions, OTOH, generate the values on the fly, only as
> they're needed, so there's no extra list left over once the dict is
> created.

And sometimes that's a win, and sometimes it's not. 

Generator expressions are more computationally expensive than lists -- 
they're functions which remember their internal state so you can pause 
them and restart them at will. That doesn't happen for free -- it takes 
memory and time. The reason Python has generator expressions is that 
for large amounts of data, the saving you have by not needing to 
produce the entire list all at once more than makes up for the extra 
cost, but for small amounts of data, that's not always the case:

[st...@sylar ~]$ python -m timeit "dict((k,k+1) for k in xrange(2))"
10 loops, best of 3: 5.89 usec per loop
[st...@sylar ~]$ python -m timeit "dict([(k,k+1) for k in xrange(2)])"
10 loops, best of 3: 4.78 usec per loop


Here, using a generator expression is a pessimation, not an 
optimization.


> Sure it will eventually be garbage collected, but "waste not, want
> not", as my grandmother used to say.

Does your grandmother have a box labelled "Pieces of string, too short 
to use" as well?



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Shashwat Anand
On Thu, Aug 19, 2010 at 8:21 PM, Pete  wrote:

> Hi,
>
> I've been reading up on list comprehensions lately, all userful and
> powerful stuff - trying to wrap my brain around it :)
>
> As the examples all seem to relate to lists, I was wondering if there is an
> elegant similar way to apply a function to all keys in a dictionary?
>
> (without looping over it, of course)
>
> I'm trying to convert all keys in a dict to uppercase, as in:
>
> INPUT:
> age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 }
>
> OUTPUT:
> age_dict = { 'PETE': 42, 'ANN': 25, 'CARL': 30, 'AMANDA': 64 }
>
> I googled 'dictionary comprehension' but couldn't get any code to work with
> the examples given.
>
> http://www.siafoo.net/article/52#dictionary-comprehensions
>
> thanks,
>

There is dict comprehension too from python2.7 onwards.

>
> Pete
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
~l0nwlf
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Wayne Werner
On Thu, Aug 19, 2010 at 10:02 AM, Vince Spicer  wrote:

> Hey you can use list comprehension here
>
>
> age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 }
>
> you can create a dict from a list of tuples and you can access the dict as
> a
> list of tuples by accessing its items
>
> Example:
>
> age_dict = dict([(key.upper(), value) for key,value in age_dict.items()])
>

This is a bad place to use a list comprehension. This will create a list of
values first and then create a dict from that list, so now you have a list
floating around that you didn't need.

Generator expressions, OTOH, generate the values on the fly, only as they're
needed, so there's no extra list left over once the dict is created.

Sure it will eventually be garbage collected, but "waste not, want not", as
my grandmother used to say.

-Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Peter Otten
Pete wrote:

> Hi,
> 
> I've been reading up on list comprehensions lately, all userful and
> powerful stuff - trying to wrap my brain around it :)
> 
> As the examples all seem to relate to lists, I was wondering if there is
> an elegant similar way to apply a function to all keys in a dictionary?
> 
> (without looping over it, of course)
> 
> I'm trying to convert all keys in a dict to uppercase, as in:
> 
> INPUT:
> age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 }
> 
> OUTPUT:
> age_dict = { 'PETE': 42, 'ANN': 25, 'CARL': 30, 'AMANDA': 64 }
> 
> I googled 'dictionary comprehension' but couldn't get any code to work
> with the examples given.

Python 2.4-2.6
>>> dict((k.upper(), v) for k, v in age_dict.iteritems())
{'PETE': 42, 'ANN': 25, 'AMANDA': 64, 'CARL': 30}

Python 2.7
>>> {k.upper(): v for k, v in age_dict.iteritems()}
{'PETE': 42, 'ANN': 25, 'AMANDA': 64, 'CARL': 30}


Python 3.x
>>> {k.upper(): v for k, v in age_dict.items()}
{'PETE': 42, 'ANN': 25, 'AMANDA': 64, 'CARL': 30}


items() instead of iteritems() works in 2.x, too, but is less efficient.

Peter

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Vince Spicer
Hey you can use list comprehension here

age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 }

you can create a dict from a list of tuples and you can access the dict as
a
list of tuples by accessing its items

Example:

age_dict = dict([(key.upper(), value) for key,value in age_dict.items()])

hope that helps,

Vince

On Thu, Aug 19, 2010 at 8:51 AM, Pete  wrote:

> Hi,
>
> I've been reading up on list comprehensions lately, all userful and
> powerful stuff - trying to wrap my brain around it :)
>
> As the examples all seem to relate to lists, I was wondering if there is an
> elegant similar way to apply a function to all keys in a dictionary?
>
> (without looping over it, of course)
>
> I'm trying to convert all keys in a dict to uppercase, as in:
>
> INPUT:
> age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 }
>
> OUTPUT:
> age_dict = { 'PETE': 42, 'ANN': 25, 'CARL': 30, 'AMANDA': 64 }
>
> I googled 'dictionary comprehension' but couldn't get any code to work with
> the examples given.
>
> http://www.siafoo.net/article/52#dictionary-comprehensions
>
> thanks,
>
> Pete
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] List comprehension for dicts?

2010-08-19 Thread Pete
Hi,

I've been reading up on list comprehensions lately, all userful and powerful 
stuff - trying to wrap my brain around it :)

As the examples all seem to relate to lists, I was wondering if there is an 
elegant similar way to apply a function to all keys in a dictionary?

(without looping over it, of course)

I'm trying to convert all keys in a dict to uppercase, as in:

INPUT:
age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 }

OUTPUT:
age_dict = { 'PETE': 42, 'ANN': 25, 'CARL': 30, 'AMANDA': 64 }

I googled 'dictionary comprehension' but couldn't get any code to work with the 
examples given.

http://www.siafoo.net/article/52#dictionary-comprehensions

thanks,

Pete
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-29 Thread Matthew Wood
On Fri, May 28, 2010 at 6:55 PM, Steven D'Aprano wrote:

> On Fri, 28 May 2010 12:00:46 pm Matthew Wood wrote:
>
> > I THOUGHT the guaranteed same-ordering of dict.keys and dict.values
> > started in python 2.6.  That was a simple mistake.
> >
> > It turns out, that's not the case.  But in general, access to dicts
> > and sets is unordered, so you can't/don't/shouldn't count on
> > ordering.
>
> You can't count on getting a *specific* order, but you can count on
> getting a *consistent* order. (So long as you don't modify the
> dictionary between calls, of course.)
>
>
> > The solution to take keys and values from dict.items()
> > DOES guarantee their ordering, even if dict.keys and dict.values
> > aren't.
>
> And so does zip(d.keys(), d.values()). They both guarantee the same
> consistent ordering.
>
> The fact is, yes, your solution does work, but your rationale for
> preferring it is irrational. That's not meant to be insulting, we all
> have preferences based on irrational little quirks, we wouldn't be
> human otherwise. When there are two equally good solutions, you have to
> pick one or the other for essentially an irrational reason -- if there
> was a rational reason to prefer one over the other, they wouldn't be
> equally good.
>
> If you choose to continue using the dict.items() solution, by all means
> do so because you like it, or because it gives you a warm fuzzy
> feeling, or because it's easier for you to remember. Or because you've
> profiled it and it is 3% faster or uses 1% less memory (I made those
> numbers up, by the way). These are all good reasons for choosing a
> solution over another solution.
>
> But stop trying to justify it on the basis of it being safer and more
> backwards compatible, because that's simply not correct. That's what
> pushes your solution out of personal preference to cargo-cult
> programming: following the form without understanding the semantics.
> The semantics of dict.keys() and values() guarantee the same order.
>
>
> [...]
> > But imagine if that guaranteed behavior started in 2.5 for example.
> > Then, if you want your code to work on 2.3, you'd definitely want to
> > pull them out of the dict via dict.items().
>
> But it didn't start in 2.5. It has been part of Python essentially
> forever. If I argued, "Imagine that dictionaries only gained an items()
> method in 2.5, and you wanted it to work in 2.3, you'd need to avoid
> dict.items()", what would you say?
>
>
> > I think your response was quite rude.
>
> If you can't take constructive criticism without getting offended and
> crying "oh how rude!", there's a serious problem.
>
>
> > I mean really, cargo cult programming?
> > I just tried to suggest a solution and I think it's crappy that you
> > accused me of "programming without understanding what you are doing".
>
> I think it is quite clear that in *this* specific case you don't
> understand what you are doing, because you are recommending a solution
> that you labelled "This line isn't necessary". If it's not necessary,
> why include it?
>
> We all code badly at times. I'm sure if you were to go through my code
> line by line, you'd find some real clangers caused by me failing to
> fully understand what I was doing too. Patches and bug reports are
> welcome :)
>
> If it makes you feel any better, I was once told by Alex Martelli (one
> of the Python demi-gods) that if he were marking my code for an
> assignment he would fail me over what I believed was a trivial
> stylistic difference of opinion. I was declaring globals even if I
> didn't assign to them, e.g.:
>
> def func(x):
>global y
>return x + y
>
> It took me a long time, perhaps a few years, but I've come around to
> Martelli's position on globals and no longer declare them unless I
> assign to them. I still think a fail over such a small issue is awfully
> harsh, but perhaps he was having a bad day. I've come to understand the
> semantics of the global statement better, and can see that unnecessary
> global declarations goes against the purpose and meaning of the
> statement. I was, in short, cargo-cult programming, using global
> without understanding it. As harsh as Martelli's response was, I
> believe I'm a better coder today because of it than if he had just
> patted me on the head and said "that's okay, you write anything you
> like".
>
>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


Well, since it appears that my offer to nip the email flame-war in the bud
was declined, I'll reluctantly respond.

And as name dropping Alex Martelli seems the order of the day, I'll go ahead
and share my experience with him as well: He decided to put my code into the
python cook book (for those that demand citations: Python Cookbook, 1st
edition, recipe 2.7, page 49).  He did so while making suggestions on how my
code could be impro

Re: [Tutor] list of dicts <-> dict of lists?

2010-05-28 Thread Luke Paireepinart
> I'm new to python, so i don't know if this is important, or what it means at 
> all.  I looked in setup.py, and it didn't tell me anything.  What does it 
> mean by "the necessary bits" were not found?

Not really sure, but in the future please create a new e-mail to
tutor@python.org rather than hijacking a thread.  And don't just hit
"reply" and delete the contents of a different e-mail, you have to
create an entirely new message.  Otherwise your message will get
threaded with that other message's thread in certain e-mail clients.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-28 Thread Karl Jansson
I was trying to build python, and this printed to the terminal:

Python build finished, but the necessary bits to build these modules were not 
found:
_gdbm  ossaudiodevreadline
spwd  
To find the necessary bits, look in setup.py in detect_modules() for the 
module's name.



I'm new to python, so i don't know if this is important, or what it means at 
all.  I looked in setup.py, and it didn't tell me anything.  What does it mean 
by "the necessary bits" were not found?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-28 Thread Steven D'Aprano
On Fri, 28 May 2010 12:00:46 pm Matthew Wood wrote:

> I THOUGHT the guaranteed same-ordering of dict.keys and dict.values
> started in python 2.6.  That was a simple mistake.
>
> It turns out, that's not the case.  But in general, access to dicts
> and sets is unordered, so you can't/don't/shouldn't count on
> ordering.

You can't count on getting a *specific* order, but you can count on 
getting a *consistent* order. (So long as you don't modify the 
dictionary between calls, of course.)


> The solution to take keys and values from dict.items() 
> DOES guarantee their ordering, even if dict.keys and dict.values
> aren't.

And so does zip(d.keys(), d.values()). They both guarantee the same 
consistent ordering.

The fact is, yes, your solution does work, but your rationale for 
preferring it is irrational. That's not meant to be insulting, we all 
have preferences based on irrational little quirks, we wouldn't be 
human otherwise. When there are two equally good solutions, you have to 
pick one or the other for essentially an irrational reason -- if there 
was a rational reason to prefer one over the other, they wouldn't be 
equally good.

If you choose to continue using the dict.items() solution, by all means 
do so because you like it, or because it gives you a warm fuzzy 
feeling, or because it's easier for you to remember. Or because you've 
profiled it and it is 3% faster or uses 1% less memory (I made those 
numbers up, by the way). These are all good reasons for choosing a 
solution over another solution.

But stop trying to justify it on the basis of it being safer and more 
backwards compatible, because that's simply not correct. That's what 
pushes your solution out of personal preference to cargo-cult 
programming: following the form without understanding the semantics. 
The semantics of dict.keys() and values() guarantee the same order.


[...]
> But imagine if that guaranteed behavior started in 2.5 for example. 
> Then, if you want your code to work on 2.3, you'd definitely want to
> pull them out of the dict via dict.items().

But it didn't start in 2.5. It has been part of Python essentially 
forever. If I argued, "Imagine that dictionaries only gained an items() 
method in 2.5, and you wanted it to work in 2.3, you'd need to avoid 
dict.items()", what would you say?


> I think your response was quite rude.

If you can't take constructive criticism without getting offended and 
crying "oh how rude!", there's a serious problem.


> I mean really, cargo cult programming?
> I just tried to suggest a solution and I think it's crappy that you
> accused me of "programming without understanding what you are doing".

I think it is quite clear that in *this* specific case you don't 
understand what you are doing, because you are recommending a solution 
that you labelled "This line isn't necessary". If it's not necessary, 
why include it?

We all code badly at times. I'm sure if you were to go through my code 
line by line, you'd find some real clangers caused by me failing to 
fully understand what I was doing too. Patches and bug reports are 
welcome :)

If it makes you feel any better, I was once told by Alex Martelli (one 
of the Python demi-gods) that if he were marking my code for an 
assignment he would fail me over what I believed was a trivial 
stylistic difference of opinion. I was declaring globals even if I 
didn't assign to them, e.g.:

def func(x):
global y
return x + y

It took me a long time, perhaps a few years, but I've come around to 
Martelli's position on globals and no longer declare them unless I 
assign to them. I still think a fail over such a small issue is awfully 
harsh, but perhaps he was having a bad day. I've come to understand the 
semantics of the global statement better, and can see that unnecessary 
global declarations goes against the purpose and meaning of the 
statement. I was, in short, cargo-cult programming, using global 
without understanding it. As harsh as Martelli's response was, I 
believe I'm a better coder today because of it than if he had just 
patted me on the head and said "that's okay, you write anything you 
like".



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-28 Thread Peter Otten
David Perlman wrote:

> Oh, except one problem: the csv.DictWriter lets you tell it what order
> you want the columns output in.  With your version, they just show up
> in whatever order Python wants them.

That's not hard to fix:

>>> fieldnames = "abca"
>>> cols = [data[fn] for fn in fieldnames]
>>> writer.writerows(zip(*cols))
1,4,7,1
2,5,8,2
3,6,9,3

Peter

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-28 Thread David Perlman
Oh, except one problem: the csv.DictWriter lets you tell it what order  
you want the columns output in.  With your version, they just show up  
in whatever order Python wants them.


On May 28, 2010, at 2:33 AM, Peter Otten wrote:


I think it's simpler and therefore more appropriate to use a normal
csv.writer here:


import csv
import sys
data = {'a': [1, 2, 3], 'c': [7, 8, 9], 'b': [4, 5, 6]}
writer = csv.writer(sys.stdout)
writer.writerow(data.keys())

a,c,b

writer.writerows(zip(*data.values()))

1,7,4
2,8,5
3,9,6


--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-28 Thread David Perlman
Aha, now this is the clever solution that I didn't find "outside the  
box".  :)


On May 28, 2010, at 2:33 AM, Peter Otten wrote:


I think it's simpler and therefore more appropriate to use a normal
csv.writer here:


import csv
import sys
data = {'a': [1, 2, 3], 'c': [7, 8, 9], 'b': [4, 5, 6]}
writer = csv.writer(sys.stdout)
writer.writerow(data.keys())

a,c,b

writer.writerows(zip(*data.values()))

1,7,4
2,8,5
3,9,6

Peter


--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-28 Thread Sander Sweers
2010/5/28 spir ☣ :
> his is a different feature from preserving *input* order of of keys, or of 
> key:value pairs.

In Python 2.7 and 3.1 [1] we now have the OrderedDict which does
preserve input order.

Greets
Sander

[1] http://www.python.org/dev/peps/pep-0372/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-28 Thread spir ☣
On Thu, 27 May 2010 20:00:46 -0600
Matthew Wood  wrote:

> I THOUGHT the guaranteed same-ordering of dict.keys and dict.values started
> in python 2.6.  That was a simple mistake.
> 
> It turns out, that's not the case.  But in general, access to dicts and sets
> is unordered, so you can't/don't/shouldn't count on ordering.  The solution
> to take keys and values from dict.items() DOES guarantee their ordering,
> even if dict.keys and dict.values aren't.

The word "order" is a bit over-used :-)
Python's guarantee is that the *output* orders of keys() & value() match each 
other. Say, they're consistent // sequences. This is a different feature from 
preserving *input* order of of keys, or of key:value pairs. (Which is not true 
is Python or Lua, for instance, but in recent Ruby versions, yes: 
http://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash/.)

Denis


vit esse estrany ☣

spir.wikidot.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-28 Thread Peter Otten
David Perlman wrote:

> Using the csv.DictReader and csv.DictWriter lets you read and write
> lists of dictionaries from files containing tabular data.  I have a
> system that naturally generates tabular data in the form of a
> dictionary of lists: the dictionary key is the name of the column, and
> then the value is a list which contains the data for that column.
> Sort of like a spreadsheet.  I would like to use csv.DictWriter to
> write out this data but that requires a list of dicts.
> 
> I can convert the dict of lists to a list of dicts, and thus make it
> compatible with csv.DictWriter, with the following ugly comprehensions:
> 
>  >>> y
> {'a': [1, 2, 3], 'c': [7, 8, 9], 'b': [4, 5, 6]}
>  >>> [dict([(i,y[i][j]) for i in y.keys()]) for j in
> range(len(y[y.keys()[0]]))]
> [{'a': 1, 'c': 7, 'b': 4}, {'a': 2, 'c': 8, 'b': 5}, {'a': 3, 'c': 9,
> 'b': 6}]
> 
> ...but I'm wondering if anyone knows of a more elegant way, perhaps
> something built-in suited for this purpose...
> 
> I am aware that any solution will only work if the lists in the dict
> are all the same length.  :)

I think it's simpler and therefore more appropriate to use a normal 
csv.writer here:

>>> import csv
>>> import sys
>>> data = {'a': [1, 2, 3], 'c': [7, 8, 9], 'b': [4, 5, 6]}
>>> writer = csv.writer(sys.stdout)
>>> writer.writerow(data.keys())
a,c,b
>>> writer.writerows(zip(*data.values()))
1,7,4
2,8,5
3,9,6

Peter

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-27 Thread Matthew Wood
Wow.  Something horrible happened here.

http://xkcd.com/386/


I THOUGHT the guaranteed same-ordering of dict.keys and dict.values started
in python 2.6.  That was a simple mistake.

It turns out, that's not the case.  But in general, access to dicts and sets
is unordered, so you can't/don't/shouldn't count on ordering.  The solution
to take keys and values from dict.items() DOES guarantee their ordering,
even if dict.keys and dict.values aren't.

That's all I was trying to say.  It's unfortunate that I had the python
version  the guaranteed same-ordering wrong.


I'm certainly not trying to say that you shouldn't trust language features.
 That's not it at all.

But imagine if that guaranteed behavior started in 2.5 for example.  Then,
if you want your code to work on 2.3, you'd definitely want to pull them out
of the dict via dict.items().



I think your response was quite rude.  I mean really, cargo cult
programming?  May John Frum forgive your unnecessary aggression.  I just
tried to suggest a solution and I think it's crappy that you accused me of
"programming without understanding what you are doing".

I recognize that you told me not to take offense; but, no offense, nobody
cared when Carrie Prejean (Miss California) said that either.



So, I do apologize for the mistake I made, and hopefully we (both you AND I)
can nip this mailing-list flame-war in the bud.



Anyway, I hope David (the original questioner) got a little help, or at
least another token for confirmation that any list comprehension solution
will be semi-ugly/semi-complex.


--

I enjoy haiku
but sometimes they don't make sense;
refrigerator?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-27 Thread Steven D'Aprano
On Fri, 28 May 2010 09:44:36 am Matthew Wood wrote:

> That said, the version with an extra line will work on python < 2.6,
> so I'd probably just leave it that way.

Why?

That's like saying:

"I could write y = x+2 in Python, but y = 1+x+1 will work too, so I'll 
write that instead, just in case."

Yes, I suppose that there are buggy Python implementations where x+2 
doesn't work correctly but 1+x+1 does, and there might be stupid data 
types that are the same, but do you really need to support such 
badly-behaved objects?



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-27 Thread Steven D'Aprano
On Fri, 28 May 2010 09:19:20 am Matthew Wood wrote:

> I BELIEVE there's some new cool features in 2.6 or maybe 3.0 where
> non-simultaneous access to my_dict.keys() and my_dict.values() will
> keep them "paired up", but I don't know the details.

This is not a new feature, but a very old feature. It became a 
guaranteed promise of the language in Python 2.0:

http://docs.python.org/release/2.0/lib/typesmapping.html

and worked at least back to Python 1.5:

[st...@sylar ~]$ python1.5
Python 1.5.2 (#1, Apr  1 2009, 22:55:54)  [GCC 4.1.2 20070925 (Red Hat 
4.1.2-27)] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> # mess with the dict a little bit
... d['a'] = -1
>>> d['f'] = -1
>>> del d['a']
>>> d['f'] = 6
>>> d['a'] = 1
>>> print d
{'f': 6, 'd': 4, 'e': 5, 'b': 2, 'c': 3, 'a': 1}
>>> d.keys()
['f', 'd', 'e', 'b', 'c', 'a']
>>> d.values()
[6, 4, 5, 2, 3, 1]


Since this is guaranteed, your comment:

> # This line isn't necessary #keys, values = zip(* y.items())
...
> But since I'm a coward, and I'd like my code to run on older versions
> of python too, I'd leave the initial step.

is unfortunately cargo-cult programming (programming without 
understanding what you are doing). This sounds bad, and it is, but 
we've all been there and done that, so don't take offence.

Firstly, it's not necessary, and secondly, even if it was necessary, it 
won't work in older versions:

>>> keys, items = zip(*d.items())
  File "", line 1
keys, items = zip(*d.items())
  ^
SyntaxError: invalid syntax


So drop it. You either trust Python, or you don't, and if you don't, you 
can't trust it to do *anything*. (If d.keys() and d.values() are buggy, 
how do you know that zip() or d.items() aren't buggy too?)

The exception to this is if you are handling non-dict mappings that 
don't make promises about keeping d.keys() and d.values() aligned in 
order. And that requires a comment to show why you're doing what 
otherwise would seen to be unnecessary work:

# Support badly-behaved mappings like mymodule.stupid_dict.
keys, items = zip(*d.items())
...

rather than:

# Appease the Python gods so they give us cargo and not bugs.
keys, values = zip(d.items())
...


See the difference between cargo cult programming and defensive 
programming?





-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-27 Thread Matthew Wood
Well, that makes a lot of sense.  I probably should have looked it up.  :-)

That said, the version with an extra line will work on python < 2.6,
so I'd probably just leave it that way.


But thanks the docs pointer.  Always useful.


That said, if I KNEW that my software was only to be implemented in
3.0 or greater, I'd go with the new, cool, slick,
shows-I-read-the-docs way!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-27 Thread Mark Lawrence

I confess that I don't like top posting :)  Please see below.

On 28/05/2010 00:19, Matthew Wood wrote:

#!/usr/bin/env python


Here's my best attempt.  I'm not sure if it's "simpler" than yours,
but for me it seems a bit cleaner.  Then again, I LOVE the zip
operator, and the '*' operator too.  :-)  Whenever I see a "transpose
this" type problem, I think zip.


y = {'a': [1, 2, 3], 'c': [7, 8, 9], 'b': [4, 5, 6]}

print y

old = [dict([(i, y[i][j]) for i in y.keys()])
   for j in range(len(y[y.keys()[0]]))]
print old


keys, values = zip(* y.items())
new = [dict([(i, j) for i, j in zip(keys, column)])
 for column in zip(* values)]

print new

print new == old

I BELIEVE there's some new cool features in 2.6 or maybe 3.0 where
non-simultaneous access to my_dict.keys() and my_dict.values() will
keep them "paired up", but I don't know the details.  If you skipped
the upper line (setting keys and values) you'd be accessing y.keys() 3
times (in this example).  I'm not sure if you're guaranteed to have
the order remain the same for all three accesses.  If that's the case,
I'd change the code to be:

# This line isn't necessary #keys, values = zip(* y.items())
new = [dict([(i, j) for i, j in zip(y.keys(), column)])
 for column in zip(* y.values())]

or even

# This line isn't necessary #keys, values = zip(* y.items())
new = [dict([(i, j) for i, j in zip(y, column)])
 for column in zip(* y.values())]



RTFM? :)  From the Python docs for 2.6.5
"items()
Return a copy of the dictionary’s list of (key, value) pairs.

CPython implementation detail: Keys and values are listed in an 
arbitrary order which is non-random, varies across Python 
implementations, and depends on the dictionary’s history of insertions 
and deletions.


If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() 
are called with no intervening modifications to the dictionary, the 
lists will directly correspond. This allows the creation of (value, key) 
pairs using zip(): pairs = zip(d.values(), d.keys()). The same 
relationship holds for the iterkeys() and itervalues() methods: pairs = 
zip(d.itervalues(), d.iterkeys()) provides the same value for pairs. 
Another way to create the same list is pairs = [(v, k) for (k, v) in 
d.iteritems()]."



But since I'm a coward, and I'd like my code to run on older versions
of python too, I'd leave the initial step.
--

I enjoy haiku
but sometimes they don't make sense;
refrigerator?


On Thu, May 27, 2010 at 4:15 PM, David Perlman  wrote:


Using the csv.DictReader and csv.DictWriter lets you read and write lists of 
dictionaries from files containing tabular data.  I have a system that 
naturally generates tabular data in the form of a dictionary of lists: the 
dictionary key is the name of the column, and then the value is a list which 
contains the data for that column.  Sort of like a spreadsheet.  I would like 
to use csv.DictWriter to write out this data but that requires a list of dicts.

I can convert the dict of lists to a list of dicts, and thus make it compatible 
with csv.DictWriter, with the following ugly comprehensions:


y

{'a': [1, 2, 3], 'c': [7, 8, 9], 'b': [4, 5, 6]}

[dict([(i,y[i][j]) for i in y.keys()]) for j in range(len(y[y.keys()[0]]))]

[{'a': 1, 'c': 7, 'b': 4}, {'a': 2, 'c': 8, 'b': 5}, {'a': 3, 'c': 9, 'b': 6}]

...but I'm wondering if anyone knows of a more elegant way, perhaps something 
built-in suited for this purpose...

I am aware that any solution will only work if the lists in the dict are all 
the same length.  :)

Thanks!


--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-27 Thread Matthew Wood
#!/usr/bin/env python


Here's my best attempt.  I'm not sure if it's "simpler" than yours,
but for me it seems a bit cleaner.  Then again, I LOVE the zip
operator, and the '*' operator too.  :-)  Whenever I see a "transpose
this" type problem, I think zip.


y = {'a': [1, 2, 3], 'c': [7, 8, 9], 'b': [4, 5, 6]}

print y

old = [dict([(i, y[i][j]) for i in y.keys()])
  for j in range(len(y[y.keys()[0]]))]
print old


keys, values = zip(* y.items())
new = [dict([(i, j) for i, j in zip(keys, column)])
    for column in zip(* values)]

print new

print new == old

I BELIEVE there's some new cool features in 2.6 or maybe 3.0 where
non-simultaneous access to my_dict.keys() and my_dict.values() will
keep them "paired up", but I don't know the details.  If you skipped
the upper line (setting keys and values) you'd be accessing y.keys() 3
times (in this example).  I'm not sure if you're guaranteed to have
the order remain the same for all three accesses.  If that's the case,
I'd change the code to be:

# This line isn't necessary #keys, values = zip(* y.items())
new = [dict([(i, j) for i, j in zip(y.keys(), column)])
for column in zip(* y.values())]

or even

# This line isn't necessary #keys, values = zip(* y.items())
new = [dict([(i, j) for i, j in zip(y, column)])
for column in zip(* y.values())]


But since I'm a coward, and I'd like my code to run on older versions
of python too, I'd leave the initial step.
--

I enjoy haiku
but sometimes they don't make sense;
refrigerator?


On Thu, May 27, 2010 at 4:15 PM, David Perlman  wrote:
>
> Using the csv.DictReader and csv.DictWriter lets you read and write lists of 
> dictionaries from files containing tabular data.  I have a system that 
> naturally generates tabular data in the form of a dictionary of lists: the 
> dictionary key is the name of the column, and then the value is a list which 
> contains the data for that column.  Sort of like a spreadsheet.  I would like 
> to use csv.DictWriter to write out this data but that requires a list of 
> dicts.
>
> I can convert the dict of lists to a list of dicts, and thus make it 
> compatible with csv.DictWriter, with the following ugly comprehensions:
>
> >>> y
> {'a': [1, 2, 3], 'c': [7, 8, 9], 'b': [4, 5, 6]}
> >>> [dict([(i,y[i][j]) for i in y.keys()]) for j in 
> >>> range(len(y[y.keys()[0]]))]
> [{'a': 1, 'c': 7, 'b': 4}, {'a': 2, 'c': 8, 'b': 5}, {'a': 3, 'c': 9, 'b': 6}]
>
> ...but I'm wondering if anyone knows of a more elegant way, perhaps something 
> built-in suited for this purpose...
>
> I am aware that any solution will only work if the lists in the dict are all 
> the same length.  :)
>
> Thanks!
>
>
> --
> -dave
> "Pseudo-colored pictures of a person's brain lighting up are
> undoubtedly more persuasive than a pattern of squiggles produced by a
> polygraph.  That could be a big problem if the goal is to get to the
> truth."  -Dr. Steven Hyman, Harvard
>
>
>
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] list of dicts <-> dict of lists?

2010-05-27 Thread David Perlman
Using the csv.DictReader and csv.DictWriter lets you read and write  
lists of dictionaries from files containing tabular data.  I have a  
system that naturally generates tabular data in the form of a  
dictionary of lists: the dictionary key is the name of the column, and  
then the value is a list which contains the data for that column.   
Sort of like a spreadsheet.  I would like to use csv.DictWriter to  
write out this data but that requires a list of dicts.


I can convert the dict of lists to a list of dicts, and thus make it  
compatible with csv.DictWriter, with the following ugly comprehensions:


>>> y
{'a': [1, 2, 3], 'c': [7, 8, 9], 'b': [4, 5, 6]}
>>> [dict([(i,y[i][j]) for i in y.keys()]) for j in  
range(len(y[y.keys()[0]]))]
[{'a': 1, 'c': 7, 'b': 4}, {'a': 2, 'c': 8, 'b': 5}, {'a': 3, 'c': 9,  
'b': 6}]


...but I'm wondering if anyone knows of a more elegant way, perhaps  
something built-in suited for this purpose...


I am aware that any solution will only work if the lists in the dict  
are all the same length.  :)


Thanks!


--
-dave
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph.  That could be a big problem if the goal is to get to the
truth."  -Dr. Steven Hyman, Harvard



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension + lambdas - strange behaviour

2010-05-07 Thread Steven D'Aprano
On Fri, 7 May 2010 05:11:38 pm spir ☣ wrote:
> On Thu, 6 May 2010 22:15:34 +0100
>
> "Alan Gauld"  wrote:
> > As others have pointed out you are returning a reference not a
> > value.

Others have said that, but it's not true. Python does not 
have "references". The Python implementation under the hood uses 
references all the time, but they aren't visible to Python code. In 
Python you have names, and objects, and nothing else.

The classic test of languages with references is, can you write a 
function that swaps two variables? That is, something like this:

>>> x = 1
>>> y = 2
>>> swap(x, y)
>>> print x, y
2, 1

But you can't do this in Python. This proves beyond all doubt that 
Python code does not have references.



> Yes. (I have said that, too.) But still there is a mystery for me.
> Better explained byt the following:
>
> x = 0 ; print id(x)   # an address

No, id(x) is an ID number, not an address. It happens to be that for 
CPython, the address of the object in the underlying implementation is 
used as the ID number, but that's an accident of implementation. They 
could have very easily decided to add 7 to the address, or multiply it 
by 3. Jython uses a completely different scheme, where ID numbers have 
nothing to do with addresses. They go 1, 2, 3, 4, ...

Python guarantees that no two objects will have the same ID number *at 
the same time*, but it makes no other promises. CPython, for example, 
re-uses ID numbers. Jython probably doesn't.


> def f() : print x # 0
> x = 1 ; print id(x)   # another one
> f()   # 1
>
> This shows, I guess, that the reference of the upvalue x is *not* an
> address. But the key (maybe the name itself ?) used by python to 
> lookup a symbol's value, in a given scope, at runtime. Indeed f must
> find its upvalue in the global scope. 

Yes. The *name* "x" is looked up in the global scope at runtime. The 
address of the object bound to x is never used by Python, except that 
CPython uses it as a ID number. 


> Note the scope must also be referenced:
>
> def f():
>   # not the global scope
>   x = 0
>   def g():
>   print x
>   x = 1
>   return g
> # global scope
> f()() # 1
>
> I guess the above example also shows that upvalues can be
> "finalised", since here the scope is lost xwhen f runs.
>
> Does anyone know if this reasoning is correct, and how this is done?


Python has the concept of names spaces. Names are strings 
like "x", "foo", "math" and so forth. When you refer to a name, Python 
searches each name space in turn:

* the local name space of the current function (if any)
* the name space of each parent function (if any) in turn
* the global name space
* the built-in name space

and then raises NameError if it doesn't find a match at all. Inside a 
class, it's a little different, but essentially follows a similar 
pattern:

* the local name space of the method
* the global name space
* built-ins
* raise NameError

Notice that the class name space is deliberately left out.

When looking up an attribute of an item, it goes something like this:


* if the class has a __getattribute__ method, call it
* the instance __slots__ (if any)
* the instance __dict__ (if it exists)
* the class __dict__
* the __dict__ of any superclasses
* if the class has a __getattr__ method, call it
* raise AttributeError


Regardless of how you look up a name or attribute, once Python finds it, 
it passes the object back to you. Actually, because objects are large 
complicated objects, the Python implementation actually passes some 
sort of internal short-cut to the object, for speed. In CPython, that 
is a pointer. In Jython, it is a reference or safe-pointer. In other 
Python implementations (IronPython, PyPy, etc.) some other mechanism is 
used.

The mechanism isn't important. From your Python code, you have no way of 
telling what the mechanism is, all you see is names ("math") and 
objects (the math module object).

In CPython, we can say some other things about the implementation of 
name spaces. In the global (top level) scope of a module, in the 
interactive interpreter, and inside a class, the name space is a 
dictionary with strings as keys. Inside functions, the name space is a 
bit more complicated: for speed it is turned into a C-level table. 
(Actually, it's a bit more complicated for classes too, with slots and 
other optimizations.) This is why Python classes have a __dict__ 
attribute, and why the dict you get back from globals() is writable, 
but changing the dict you get back from locals() has no effect inside a 
function.

Objects can have any number of names. If you do this:

a = b = c = d = 42
e = c

then you have given the object 42 five distinct names. But if you do 
this:

mylist = []
mylist.append(20 + 3)

the object 23 is created and stored inside a list, but it has no name. 
It is an anonymous object, but you can still refer to it:

mylist[0]  # gives 23

Some operations do a re-binding

Re: [Tutor] List comprehension + lambdas - strange behaviour

2010-05-07 Thread spir ☣
On Thu, 6 May 2010 22:15:34 +0100
"Alan Gauld"  wrote:

> As others have pointed out you are returning a reference not a value.

Yes. (I have said that, too.) But still there is a mystery for me. Better 
explained byt the following:

x = 0 ; print id(x) # an address
def f() : print x   # 0
x = 1 ; print id(x) # another one
f() # 1

This shows, I guess, that the reference of the upvalue x is *not* an address. 
But the key (maybe the name itself ?) used by python to lookup a symbol's 
value, in a given scope, at runtime. Indeed f must find its upvalue in the 
global scope. Note the scope must also be referenced:

def f():
# not the global scope
x = 0
def g():
print x
x = 1
return g
# global scope
f()()   # 1

I guess the above example also shows that upvalues can be "finalised", since 
here the scope is lost xwhen f runs.

Does anyone know if this reasoning is correct, and how this is done?

All of this mechanics looks very complicated. I would be happy with setting 
func attributes like x here as func attributes directly & explicitely:

def f():
def g():
print g.x
g.x = 1

... which are still modifiable --explicitely.

Denis


vit esse estrany ☣

spir.wikidot.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension + lambdas - strange behaviour

2010-05-06 Thread Alan Gauld

I found this strange behaviour of lambdas, closures and list
comprehensions:

  

funs = [lambda: x for x in range(5)]
[f() for f in funs]


[4, 4, 4, 4, 4]

Of course I was expecting the list [0, 1, 2, 3, 4] as the result. The
'x' was bound to the final value of 'range(5)' expression for ALL
defined functions. Can you explain this? Is this only counterintuitive
example or an error in CPython?


As others have pointed out you are returning a reference not a value.

You can do what you want by defining a lo cal closure using:

funs = [lambda y = x: y for x in range(5)]

Now you can do

for f in funs:
   print f()

and get the answer you expect.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension + lambdas - strange behaviour

2010-05-06 Thread spir ☣
On Thu, 06 May 2010 16:53:07 -0300
Ricardo Aráoz  wrote:

> So you see, your functions just return the value of x. That's because
> the lambda have no parameter, so x refers to the global name x.

In other words, the "upvalue" (the variable captured in the closure) is 
referenced. Meaning if you later change it, the closure sees the change. The 
same in other dynamic languages.
If you want the value to be captured in each func, use a second lambda to pass 
it:
>>> funcs = [(lambda a: (lambda: a))(x) for x in range(5)]
>>> [f() for f in funcs]
[0, 1, 2, 3, 4]

Or even ;-):
>>> [(lambda a: (lambda: a))(x)() for x in range(5)]
[0, 1, 2, 3, 4]

... but --> KISS principle http://en.wikipedia.org/wiki/Keep_it_simple_stupid
Such syntaxes are only good for creating problems, imo. Why not make your life 
simple? (exception: for exploring the language's guts)

Denis


vit esse estrany ☣

spir.wikidot.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension + lambdas - strange behaviour

2010-05-06 Thread Ricardo Aráoz
Artur Siekielski wrote:
> Hello.
> I found this strange behaviour of lambdas, closures and list
> comprehensions:
>
>   
 funs = [lambda: x for x in range(5)]
 [f() for f in funs]
 
> [4, 4, 4, 4, 4]
>
> Of course I was expecting the list [0, 1, 2, 3, 4] as the result. The
> 'x' was bound to the final value of 'range(5)' expression for ALL
> defined functions. Can you explain this? Is this only counterintuitive
> example or an error in CPython?
>
>
> Regards,
> Artur
>   
Check this :
>>> funs = [(lambda: x) for x in range(5)]
>>> funs[0]()
4
>>> x
4
>>> x = 3
>>> funs[0]()
3
>>> del x
>>> funs[0]()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1, in 
NameError: global name 'x' is not defined

So you see, your functions just return the value of x. That's because
the lambda have no parameter, so x refers to the global name x.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] List index usage: is there a more pythonesque way?

2010-04-19 Thread C M Caine
Spir sent this solely to me by accident, I think.


-- Forwarded message --
From: spir ☣ 
Date: 2010/4/19
Subject: Re: [Tutor] List index usage: is there a more pythonesque way?
To: cmca...@googlemail.com


On Mon, 19 Apr 2010 12:59:40 +0100
C M Caine  wrote:

> That's the first I've read of iterating through dictionaries, I'd
> assumed it was impossible because they're unordered.

Hem, actually "ordered" and "unordered" mean whether the order is
meaningful or not. There are at least 2 implicit orders for each
collection:
* There order in which they where put in.
* The order in which they iterated.
But these can be meaningless, in the sense of arbitrary, like the
alphabetic order. As an example, consider a 'friends' collections:
* If it's just a group of friends, then it's unordered and maps to a
set data structure in python (and computer science, and maths).
* If they are put in the collection eg by favor (best friend first or
last), then it's an ordered *sequence*, and maps to a list data
structure in python (and numerous other languages).
As a consequence, precisely because order is meaningful, another
difference is a sequence can hold several times the same item, while
it makes no sense for a set.

[The choice of the term "list" is imo rather misleading. Eg a shopping
list does not mean one must buy the items in order ;-)]


Denis


vit esse estrany ☣

spir.wikidot.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List index usage: is there a more pythonesque way?

2010-04-19 Thread Wayne Werner
On Mon, Apr 19, 2010 at 9:23 AM, Alan Gauld wrote:

>
> "C M Caine"  wrote
>
>> That's the first I've read of iterating through dictionaries, I'd
>>
>> assumed it was impossible because they're unordered.
>>
>
> Iteration doesn't require order, only to get each item once.
> Even in very old Python versions you could iterate a dictionary via the
> keys() method. More recently you can do it directly - although the effect is
> the same. There is no guarantee of order only that you process every item
> once.


And of course if you want to get the items sorted you can iterate over
sorted(mydict.keys()).

-Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List index usage: is there a more pythonesque way?

2010-04-19 Thread Alan Gauld


"C M Caine"  wrote 


That's the first I've read of iterating through dictionaries, I'd
assumed it was impossible because they're unordered. 


Iteration doesn't require order, only to get each item once.
Even in very old Python versions you could iterate a dictionary 
via the keys() method. More recently you can do it directly - although 
the effect is the same. There is no guarantee of order only that 
you process every item once.


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List index usage: is there a more pythonesque way?

2010-04-19 Thread C M Caine
That's the first I've read of iterating through dictionaries, I'd
assumed it was impossible because they're unordered. Your explanation
for defining your own iterables is much easier to understand than the
one I read before as well.

Thanks again.

2010/4/19 spir ☣ :
> On Mon, 19 Apr 2010 00:37:11 +0100
> C M Caine  wrote:
>
>> That's two new things I've learnt. I didn't realise that for loops
>> could be used like that (with more than one... key?).
>
> Consider considering things differently: a for loop always iterates over 
> items of a collection you indicate:
>
> l = [1,2,3]
> # item is list item             (implicit, it could be written items(l) or 
> l.items())
> for n in l: print n,
> # item is (index,item) pair
> for (i,n) in enumerate(l): print (i,n),
> print
>
> d = {'a':1, 'b':2, 'c':3}
> # item is dict key              (implicit, it could be written d.keys())
> for k in d: print k,
> # item is dict value
> for v in d.values(): print v,
> # item is (key,value) pair
> for (k,v) in d.items(): print (k,v),
> print
>
> (In the last case "items()" is maybe a bit confusing.)
>
> Python lets you construct your own iterators on custom collections to iterate 
> in a different way:
> class NestedList(list):
>        def __iter__(self):
>                ll = list.__iter__(self)
>                for l in ll:
>                        for item in l:
>                                yield item
> ll = NestedList([[1,2,3], [9,8]])
> for n in ll: print n,
>
> Denis
> 
>
> vit esse estrany ☣
>
> spir.wikidot.com
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List index usage: is there a more pythonesque way?

2010-04-19 Thread spir ☣
On Mon, 19 Apr 2010 00:37:11 +0100
C M Caine  wrote:

> That's two new things I've learnt. I didn't realise that for loops
> could be used like that (with more than one... key?).

Consider considering things differently: a for loop always iterates over items 
of a collection you indicate:

l = [1,2,3]
# item is list item (implicit, it could be written items(l) or 
l.items())
for n in l: print n,
# item is (index,item) pair
for (i,n) in enumerate(l): print (i,n),
print

d = {'a':1, 'b':2, 'c':3}
# item is dict key  (implicit, it could be written d.keys())
for k in d: print k,
# item is dict value
for v in d.values(): print v,
# item is (key,value) pair
for (k,v) in d.items(): print (k,v),
print

(In the last case "items()" is maybe a bit confusing.)

Python lets you construct your own iterators on custom collections to iterate 
in a different way:
class NestedList(list):
def __iter__(self):
ll = list.__iter__(self)
for l in ll:
for item in l:
yield item
ll = NestedList([[1,2,3], [9,8]])
for n in ll: print n,

Denis


vit esse estrany ☣

spir.wikidot.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List index usage: is there a more pythonesque way?

2010-04-19 Thread ALAN GAULD
> That's two new things I've learnt. I didn't realise that for loops
> could be used like that (with more than one... key?).

Technically its still one key but enumerate returns a tuple 
of index and value and we use tuple unpacking to assign 
the values to the loop variables. That is we could write it like:

for tup in enumerate(sequence):
 index = tup[0]
 value = tup[1]
 # process stufff here
OR:
for tup in enumerate(sequence):
 index,value  = tup
 # process stufff here

Which becomes
for index, value in enumerate(sequence):
 # process stufff here

HTH,

Alan G.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List index usage: is there a more pythonesque way?

2010-04-18 Thread C M Caine
> Something is wrong in the following if statement, as both paths execute the
> same code.
>
>>             if spaceDict['1st'+key] == 0:
>>                 spaceDict['nth'+key] = i
>>             else:
>>                 spaceDict['nth'+key] = i
>>         for form in forms:
>>             adjustedSpaceDict[form] = spaceDict['nth'+form] - \
>>                                       spaceDict['1st'+form]
>>         return (numDict, adjustedSpaceDict)


Oh yeah, I think I pulled up an old version of the source file by
accident, I've fixed that bug already.
The correct code is:

# stuff...
             if spaceDict['1st'+key] == 0:
                 spaceDict['1st'+key] = i
             else:
                 spaceDict['nth'+key] = i
         for form in forms:
             adjustedSpaceDict[form] = spaceDict['nth'+form] - \
                                       spaceDict['1st'+form]
         return (numDict, adjustedSpaceDict)

I don't think I'll use defaultdict here, though thanks for pointing it
out to me, that's the first time I've heard of it; I'm trying to keep
the number of outside modules to a minimum as this is an assessed
piece of work.

Thanks, Bob.


On 19 April 2010 00:34, bob gailer  wrote:
> On 4/18/2010 6:53 PM, C M Caine wrote:
>>
>> # Example data for forms and timetable:
>> forms = ["P7", "P8", "P9", "P10", "P11", "S7", "S8", "S9", "S10",
>> "S11", "IMA", "CAT", "FOR", "RLS", "EMPTY"]
>>
>> timetable = ['CAT', 'P10', 'P8', 'EMPTY', 'EMPTY', 'EMPTY', 'S10',
>> 'S8', 'IMA', 'EMPTY', 'S7', 'S10', 'P9', 'EMPTY', 'EMPTY', 'EMPTY',
>> 'S7', 'EMPTY', 'EMPTY', 'RLS', 'FOR', 'EMPTY', 'EMPTY', 'EMPTY', 'S9',
>> 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY',
>> 'EMPTY', 'EMPTY', 'S8', 'IMA', 'S11', 'P8', 'EMPTY', 'IMA', 'EMPTY',
>> 'EMPTY', 'S11', 'S11', 'EMPTY', 'EMPTY', 'EMPTY', 'P7', 'S9', 'P11',
>> 'P11', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY',
>> 'EMPTY', 'EMPTY', 'P9', 'EMPTY', 'EMPTY', 'P8', 'FOR', 'S10', 'S11',
>> 'S7', 'P7', 'EMPTY', 'EMPTY', 'IMA', 'EMPTY', 'S9', 'P10', 'P11',
>> 'CAT', 'S8', 'P9', 'RLS']
>>
>> def analyseTimetable():
>>         "Find number of and spaces between each form."
>>
>
> Consider using defaultdict in the collections module. The first time a key
> is referenced it is automatically added with a specified value.
>
>
> import collections
>         numDict = collections.defaultdict(0)
>         spaceDict = collections.defaultdict(0)
>
>>         adjustedSpaceDict = {}
>>
>
> If you use enumerate then you can replace timetable[i] with key
>>
>>         for i, key in enumerate(timetable):
>>             numDict[key] += 1
>>
>
> Something is wrong in the following if statement, as both paths execute the
> same code.
>
>>             if spaceDict['1st'+key] == 0:
>>                 spaceDict['nth'+key] = i
>>             else:
>>                 spaceDict['nth'+key] = i
>>         for form in forms:
>>             adjustedSpaceDict[form] = spaceDict['nth'+form] - \
>>                                       spaceDict['1st'+form]
>>         return (numDict, adjustedSpaceDict)
>>
>> # End example
>>
>> This function works fine, but I think that using range(len(timetable))
>> is clumsy. On the other hand, I need the indexes to track the number
>> of spaces between instances of each form. Without using another loop
>> (so not using list.index), is there a way of getting the index of the
>> list entries?
>
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List index usage: is there a more pythonesque way?

2010-04-18 Thread C M Caine
That's two new things I've learnt. I didn't realise that for loops
could be used like that (with more than one... key?).

Thanks, I'm changing my code even now!

On 19 April 2010 00:09, Alan Gauld  wrote:
>
> "C M Caine"  wrote
>
>>       for i in range(len(timetable)):
>>           numDict[timetable[i]] += 1
>>           if spaceDict['1st'+timetable[i]] == 0:
>>               spaceDict['nth'+timetable[i]] = i
>
> for index, item in enumerate(timetable):
>           numDict[item] += 1
>           if spaceDict['1st'+item] == 0:
>               spaceDict['nth'+item] = i
>
>>
>> This function works fine, but I think that using range(len(timetable))
>> is clumsy. On the other hand, I need the indexes to track the number
>
> enumerate() is your friend.
>
>
> HTH,
>
> Alan G
>
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List index usage: is there a more pythonesque way?

2010-04-18 Thread bob gailer

On 4/18/2010 6:53 PM, C M Caine wrote:

# Example data for forms and timetable:
forms = ["P7", "P8", "P9", "P10", "P11", "S7", "S8", "S9", "S10",
"S11", "IMA", "CAT", "FOR", "RLS", "EMPTY"]

timetable = ['CAT', 'P10', 'P8', 'EMPTY', 'EMPTY', 'EMPTY', 'S10',
'S8', 'IMA', 'EMPTY', 'S7', 'S10', 'P9', 'EMPTY', 'EMPTY', 'EMPTY',
'S7', 'EMPTY', 'EMPTY', 'RLS', 'FOR', 'EMPTY', 'EMPTY', 'EMPTY', 'S9',
'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY',
'EMPTY', 'EMPTY', 'S8', 'IMA', 'S11', 'P8', 'EMPTY', 'IMA', 'EMPTY',
'EMPTY', 'S11', 'S11', 'EMPTY', 'EMPTY', 'EMPTY', 'P7', 'S9', 'P11',
'P11', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY',
'EMPTY', 'EMPTY', 'P9', 'EMPTY', 'EMPTY', 'P8', 'FOR', 'S10', 'S11',
'S7', 'P7', 'EMPTY', 'EMPTY', 'IMA', 'EMPTY', 'S9', 'P10', 'P11',
'CAT', 'S8', 'P9', 'RLS']

def analyseTimetable():
 "Find number of and spaces between each form."
   


Consider using defaultdict in the collections module. The first time a 
key is referenced it is automatically added with a specified value.





import collections
 numDict = collections.defaultdict(0)
 spaceDict = collections.defaultdict(0)


 adjustedSpaceDict = {}
   


If you use enumerate then you can replace timetable[i] with key

 for i, key in enumerate(timetable):
 numDict[key] += 1
   


Something is wrong in the following if statement, as both paths execute 
the same code.



 if spaceDict['1st'+key] == 0:
 spaceDict['nth'+key] = i
 else:
 spaceDict['nth'+key] = i
 for form in forms:
 adjustedSpaceDict[form] = spaceDict['nth'+form] - \
   spaceDict['1st'+form]
 return (numDict, adjustedSpaceDict)

# End example

This function works fine, but I think that using range(len(timetable))
is clumsy. On the other hand, I need the indexes to track the number
of spaces between instances of each form. Without using another loop
(so not using list.index), is there a way of getting the index of the
list entries?



--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List index usage: is there a more pythonesque way?

2010-04-18 Thread Alan Gauld


"C M Caine"  wrote 




   for i in range(len(timetable)):
   numDict[timetable[i]] += 1
   if spaceDict['1st'+timetable[i]] == 0:
   spaceDict['nth'+timetable[i]] = i


for index, item in enumerate(timetable):
   numDict[item] += 1
   if spaceDict['1st'+item] == 0:
   spaceDict['nth'+item] = i


This function works fine, but I think that using range(len(timetable))
is clumsy. On the other hand, I need the indexes to track the number


enumerate() is your friend.


HTH,

Alan G

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] List index usage: is there a more pythonesque way?

2010-04-18 Thread C M Caine
# Example data for forms and timetable:
forms = ["P7", "P8", "P9", "P10", "P11", "S7", "S8", "S9", "S10",
"S11", "IMA", "CAT", "FOR", "RLS", "EMPTY"]

timetable = ['CAT', 'P10', 'P8', 'EMPTY', 'EMPTY', 'EMPTY', 'S10',
'S8', 'IMA', 'EMPTY', 'S7', 'S10', 'P9', 'EMPTY', 'EMPTY', 'EMPTY',
'S7', 'EMPTY', 'EMPTY', 'RLS', 'FOR', 'EMPTY', 'EMPTY', 'EMPTY', 'S9',
'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY',
'EMPTY', 'EMPTY', 'S8', 'IMA', 'S11', 'P8', 'EMPTY', 'IMA', 'EMPTY',
'EMPTY', 'S11', 'S11', 'EMPTY', 'EMPTY', 'EMPTY', 'P7', 'S9', 'P11',
'P11', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY',
'EMPTY', 'EMPTY', 'P9', 'EMPTY', 'EMPTY', 'P8', 'FOR', 'S10', 'S11',
'S7', 'P7', 'EMPTY', 'EMPTY', 'IMA', 'EMPTY', 'S9', 'P10', 'P11',
'CAT', 'S8', 'P9', 'RLS']

def analyseTimetable():
"Find number of and spaces between each form."
numDict = {}
spaceDict = {}
adjustedSpaceDict = {}
for form in forms:
numDict[form], spaceDict['1st'+form], spaceDict['nth'+form] \
   = 0,0,0
for i in range(len(timetable)):
numDict[timetable[i]] += 1
if spaceDict['1st'+timetable[i]] == 0:
spaceDict['nth'+timetable[i]] = i
else:
spaceDict['nth'+timetable[i]] = i
for form in forms:
adjustedSpaceDict[form] = spaceDict['nth'+form] - \
  spaceDict['1st'+form]
return (numDict, adjustedSpaceDict)

# End example

This function works fine, but I think that using range(len(timetable))
is clumsy. On the other hand, I need the indexes to track the number
of spaces between instances of each form. Without using another loop
(so not using list.index), is there a way of getting the index of the
list entries?

Thanks in advance,
Colin Caine
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread Alan Gauld

"Steven D'Aprano"  wrote


List comps can include *any* comparison:

[x+1 for x in data if (3*x+2)**2 > 100*x or x < -5]


Sure, but the wording suggested (maybe wrongly) that the OP 
was a real beginner and so the concept of an expression 
was likely to be foreign. Sticking with equalty or inequality 
seemed likely to be the most familiar test to him/her.


Trying to explain the differnce between is and == seemed 
like it would be a diversion from the primary objective, 
namely how to filter a list comp.


However I guess this discussion has covered that topic too
now, so once again we have managed to kill several 
sparrows with one round of buckshot... :-)



--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread Steven D'Aprano
On Thu, 4 Mar 2010 05:18:40 am Alan Gauld wrote:
> "Steven D'Aprano"  wrote
>
> > Comparisons with None almost always should be one of:
> >
> > item is None
> > item is not None
>
> Yes, but the reason I changed it (I originally had "is not") is that
> != is a more general test for illustrating the use of 'if' within a
> LC which seemed to be the real issue within the question.

List comps can include *any* comparison:

[x+1 for x in data if (3*x+2)**2 > 100*x or x < -5]





-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread Alan Gauld

"Steven D'Aprano"  wrote


Comparisons with None almost always should be one of:

item is None
item is not None


Yes, but the reason I changed it (I originally had "is not") is that != is
a more general test for illustrating the use of 'if' within a LC which
seemed to be the real issue within the question.

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread Steven D'Aprano
On Wed, 3 Mar 2010 07:46:39 pm Alan Gauld wrote:

> mylist = [irtem for item in aList where item != None]

Comparisons with None almost always should be one of:

item is None
item is not None

The reason is that "item is None" is ONLY ever true if the item actually 
is the singleton object None (accept no substitutes!).

On the other hand, "item == None" might be true for some customer items. 
So if you actually *do* want to accept substitutes, you can use ==, but 
that would be an unusual thing to do, and worthy of a comment 
explaining that you did mean == and it isn't a mistake.

Likewise for "item != None" versus "item is not None".



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread C.T. Matsumoto

Dave Angel wrote:

Jojo Mwebaze wrote:

Hi There,

i would like to implement the following in lists

assuming

x = 3
y = 4
z = None

i want to create a dynamic list such that

mylist = [ x , y, z ] ,   if z in not None

if z is None then

mylist = [x,y]

Anyhelp!

cheers

Jojo

  


Are there any constraints on x and y ?  If you want to throw out all 
None values, then it's a ready problem.  You try it, and if it doesn't 
quite work, post the code. We'll try to help.


But if only the third value is special, then there's little point in 
making a comprehension of one value.  Just conditionally append the z 
value to the list containing x and y.


DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Hello,

I wrote a solution which isn't correct.

>>> [i for i in mylist if i]
[3, 4]


The if condition should test like the other examples given to the list.

>>> [i for i in mylist if i != None]
[3, 4]

'if i' would also leave out the integer 0.

T
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread Jojo Mwebaze
Thanks to everyone, nice ideas!
cheers


On Wed, Mar 3, 2010 at 10:02 AM, Christian Witts wrote:

> Jojo Mwebaze wrote:
>
>> Hi There,
>>
>> i would like to implement the following in lists
>>
>> assuming
>>
>> x = 3
>> y = 4
>> z = None
>>
>> i want to create a dynamic list such that
>>
>> mylist = [ x , y, z ] ,   if z in not None
>>
>> if z is None then
>>
>> mylist = [x,y]
>>
>> Anyhelp!
>>
>> cheers
>>
>> Jojo
>>
>>
>>
>>
>>
>> 
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
>  |  for , 
>
> So something like `x**2 for x in [1, 2, 3, 4, 5, None, 9] if x != None`
> would iterate over your input set pumping the current item into the variable
> x, it will check "if x != None" and if that condition evaluates true it will
> perform the function you set out to perform.
>
> The predicate section acts as a filter to your data set ensuring the
> variable you are working with meets certain conditions.  If you wanted to
> for eg. still accept the None but perform a different function on it Python
> does allow it like `x**2 if x else 'Not a number' for x in [1, 2, 3, 4, 5,
> None, 9]`.
>
> Hope that helps.
>
> --
> Kind Regards,
> Christian Witts
>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread Dave Angel

Jojo Mwebaze wrote:

Hi There,

i would like to implement the following in lists

assuming

x = 3
y = 4
z = None

i want to create a dynamic list such that

mylist = [ x , y, z ] ,   if z in not None

if z is None then

mylist = [x,y]

Anyhelp!

cheers

Jojo

  


Are there any constraints on x and y ?  If you want to throw out all 
None values, then it's a ready problem.  You try it, and if it doesn't 
quite work, post the code. We'll try to help.


But if only the third value is special, then there's little point in 
making a comprehension of one value.  Just conditionally append the z 
value to the list containing x and y.


DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread Christian Witts

Jojo Mwebaze wrote:

Hi There,

i would like to implement the following in lists

assuming

x = 3
y = 4
z = None

i want to create a dynamic list such that

mylist = [ x , y, z ] ,   if z in not None

if z is None then

mylist = [x,y]

Anyhelp!

cheers

Jojo







___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
  


 |  for , 

So something like `x**2 for x in [1, 2, 3, 4, 5, None, 9] if x != None` 
would iterate over your input set pumping the current item into the 
variable x, it will check "if x != None" and if that condition evaluates 
true it will perform the function you set out to perform.


The predicate section acts as a filter to your data set ensuring the 
variable you are working with meets certain conditions.  If you wanted 
to for eg. still accept the None but perform a different function on it 
Python does allow it like `x**2 if x else 'Not a number' for x in [1, 2, 
3, 4, 5, None, 9]`.


Hope that helps.

--
Kind Regards,
Christian Witts


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread C.T. Matsumoto

Jojo Mwebaze wrote:

Hi There,

i would like to implement the following in lists

assuming

x = 3
y = 4
z = None

i want to create a dynamic list such that

mylist = [ x , y, z ] ,   if z in not None

if z is None then

mylist = [x,y]

Anyhelp!

cheers

Jojo







___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
  

Yes a list comprehension can have if statements.

You can get the values of x and y pretty simply:

>>> [i for i in mylist if i]
[3, 4]


T
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread Alan Gauld


"Jojo Mwebaze"  wrote


i would like to implement the following in lists

assuming

x = 3
y = 4
z = None

i want to create a dynamic list such that

mylist = [ x , y, z ] ,   if z in not None

if z is None then

mylist = [x,y]



Assuming you actually mean that you don;t want to include 
any item that is None you can use an if clause at the end 
of the comprehension:


mylist = [irtem for item in aList where item != None]

and aList is any list, which could be [x,y,z] in your example.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] List comprehension possible with condition statements?

2010-03-03 Thread Jojo Mwebaze
Hi There,

i would like to implement the following in lists

assuming

x = 3
y = 4
z = None

i want to create a dynamic list such that

mylist = [ x , y, z ] ,   if z in not None

if z is None then

mylist = [x,y]

Anyhelp!

cheers

Jojo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list to numpy record array

2010-02-23 Thread Vincent Davis
@Skipper

Thanks I will post over on the scipy list

  *Vincent Davis
720-301-3003 *
vinc...@vincentdavis.net
 my blog  |
LinkedIn


On Tue, Feb 23, 2010 at 10:55 AM, Skipper Seabold wrote:

> On Mon, Feb 22, 2010 at 11:50 PM, Vincent Davis
>  wrote:
> >
> > I must be missing something simple. I have a list of lists data = "[['
>  0', '  0', '234.0', '24.0', ' 25'], ['  1', '  0', '22428.0', '2378.1', '
> 25'],.." and what to make a record array from it but it gets screwed up
> or I don't get it, maybe both. Notice that at this stage the items are
> strings, not numbers, and there is whitespace not sure this matters.
> > Here is what is happening
> > adata = numpy.array(data,numpy.float64)
> >
> > >>> adata
> > array([[  0.e+00,   0.e+00,   2.3400e+02,
> >   2.4000e+01,   2.5000e+01],
> >...,
> >[  4.7700e+02,   4.7700e+02,   2.0700e+02,
> >   4.5800e+01,   2.5000e+01]])
> >
> > This is what I would expect except it is not a record array.
> > This is not what I expect. I think I have tried every iteration including
> using numpy dtaypes numpy.int32 or bdata = numpy.array(data, dtype = [('x',
> int),('y', int),('mean',float),('stdv',float),('npixcels',int)])
> > What am I missing?
> >
> > bdata = numpy.array(data, [('x', int),('y',
> int),('mean',float),('stdv',float),('npixcels',int)])
> > >>> bdata
> > array([[(3153952, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0),
> > (206933603122, 0, 0.0, 0.0, 0), (808334386, 0, 0.0, 0.0, 0),
> > (3486240, 0, 0.0, 0.0, 0)],
> >[(3219488, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0),
> > (1356161439282, 0, 0.0, 0.0, 0),
> > (54074581398322, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)],
> >[(3285024, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0),
> > (206933931058, 0, 0.0, 0.0, 0), (925775666, 0, 0.0, 0.0, 0),
> > (3486240, 0, 0.0, 0.0, 0)],
> >...,
> >[(3487540, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0),
> > (206933602866, 0, 0.0, 0.0, 0), (908996661, 0, 0.0, 0.0, 0),
> > (3486240, 0, 0.0, 0.0, 0)],
> >[(3553076, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0),
> > (13561596370041137, 0, 0.0, 0.0, 0),
> > (62870573495603, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)],
> >[(3618612, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0),
> > (206933798962, 0, 0.0, 0.0, 0), (942552372, 0, 0.0, 0.0, 0),
> > (3486240, 0, 0.0, 0.0, 0)]],
> >
> >   dtype=[('x', ' ' >
> >
>
> I neglected to reply to the whole list on my first try.  For posterity's
> sake:
>
> You should ask on the scipy-user list with a self-contained example.
> It is heavily trafficked. http://www.scipy.org/Mailing_Lists
>
> From the example you gave above, I am not sure what's going unless
> it's something in the casting from strings.  Note though that you have
> created a structured array and not a record array.  The subtle
> difference is that the record array allows attribute lookup ie., you
> could do bdata.x instead of bdata['x'].  Structured arrays are usually
> faster as the attribute lookup convenience is implemented in Python
> whereas the structured arrays use C code.
>
> hth,
>
> Skipper
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list to numpy record array

2010-02-23 Thread Skipper Seabold
On Mon, Feb 22, 2010 at 11:50 PM, Vincent Davis
 wrote:
>
> I must be missing something simple. I have a list of lists data = "[['  0', ' 
>  0', '234.0', '24.0', ' 25'], ['  1', '  0', '22428.0', '2378.1', ' 
> 25'],.." and what to make a record array from it but it gets screwed up 
> or I don't get it, maybe both. Notice that at this stage the items are 
> strings, not numbers, and there is whitespace not sure this matters.
> Here is what is happening
> adata = numpy.array(data,numpy.float64)
>
> >>> adata
> array([[  0.e+00,   0.e+00,   2.3400e+02,
>           2.4000e+01,   2.5000e+01],
>        ...,
>        [  4.7700e+02,   4.7700e+02,   2.0700e+02,
>           4.5800e+01,   2.5000e+01]])
>
> This is what I would expect except it is not a record array.
> This is not what I expect. I think I have tried every iteration including 
> using numpy dtaypes numpy.int32 or bdata = numpy.array(data, dtype = [('x', 
> int),('y', int),('mean',float),('stdv',float),('npixcels',int)])
> What am I missing?
>
> bdata = numpy.array(data, [('x', int),('y', 
> int),('mean',float),('stdv',float),('npixcels',int)])
> >>> bdata
> array([[(3153952, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0),
>         (206933603122, 0, 0.0, 0.0, 0), (808334386, 0, 0.0, 0.0, 0),
>         (3486240, 0, 0.0, 0.0, 0)],
>        [(3219488, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0),
>         (1356161439282, 0, 0.0, 0.0, 0),
>         (54074581398322, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)],
>        [(3285024, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0),
>         (206933931058, 0, 0.0, 0.0, 0), (925775666, 0, 0.0, 0.0, 0),
>         (3486240, 0, 0.0, 0.0, 0)],
>        ...,
>        [(3487540, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0),
>         (206933602866, 0, 0.0, 0.0, 0), (908996661, 0, 0.0, 0.0, 0),
>         (3486240, 0, 0.0, 0.0, 0)],
>        [(3553076, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0),
>         (13561596370041137, 0, 0.0, 0.0, 0),
>         (62870573495603, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)],
>        [(3618612, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0),
>         (206933798962, 0, 0.0, 0.0, 0), (942552372, 0, 0.0, 0.0, 0),
>         (3486240, 0, 0.0, 0.0, 0)]],
>
>       dtype=[('x', ' ('npixcels', '
>

I neglected to reply to the whole list on my first try.  For posterity's sake:

You should ask on the scipy-user list with a self-contained example.
It is heavily trafficked. http://www.scipy.org/Mailing_Lists

>From the example you gave above, I am not sure what's going unless
it's something in the casting from strings.  Note though that you have
created a structured array and not a record array.  The subtle
difference is that the record array allows attribute lookup ie., you
could do bdata.x instead of bdata['x'].  Structured arrays are usually
faster as the attribute lookup convenience is implemented in Python
whereas the structured arrays use C code.

hth,

Skipper
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list to numpy record array

2010-02-23 Thread Vincent Davis
@Kent
All I know about RecordArrays is from reading this page:
http://www.scipy.org/RecordArrays
but it looks like you have done the right thing and created a
RecordArray. What is wrong with this result?

The number are completely different, or I have no idea how to read it.
Here are the first row of each
normal array  ['  0', '  0', '234.0', '24.0', ' 25']
Record array  [(3153952, 0, 0.0, 0.0, 0)

*Vincent Davis
720-301-3003 *
vinc...@vincentdavis.net
 my blog  |
LinkedIn


On Tue, Feb 23, 2010 at 6:30 AM, Kent Johnson  wrote:

> On Mon, Feb 22, 2010 at 11:50 PM, Vincent Davis
>  wrote:
> >
> > I must be missing something simple. I have a list of lists data = "[['
>  0', '  0', '234.0', '24.0', ' 25'], ['  1', '  0', '22428.0', '2378.1', '
> 25'],.." and what to make a record array from it but it gets screwed up
> or I don't get it, maybe both.
> >
> > bdata = numpy.array(data, [('x', int),('y',
> int),('mean',float),('stdv',float),('npixcels',int)])
> > >>> bdata
> > array([[(3153952, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0),
> ...
> > (3486240, 0, 0.0, 0.0, 0)]],
> >
> >   dtype=[('x', ' '
> All I know about RecordArrays is from reading this page:
> http://www.scipy.org/RecordArrays
> but it looks like you have done the right thing and created a
> RecordArray. What is wrong with this result?
>
> Kent
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list to numpy record array

2010-02-23 Thread Kent Johnson
On Mon, Feb 22, 2010 at 11:50 PM, Vincent Davis
 wrote:
>
> I must be missing something simple. I have a list of lists data = "[['  0', ' 
>  0', '234.0', '24.0', ' 25'], ['  1', '  0', '22428.0', '2378.1', ' 
> 25'],.." and what to make a record array from it but it gets screwed up 
> or I don't get it, maybe both.
>
> bdata = numpy.array(data, [('x', int),('y', 
> int),('mean',float),('stdv',float),('npixcels',int)])
> >>> bdata
> array([[(3153952, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0),
...
>         (3486240, 0, 0.0, 0.0, 0)]],
>
>       dtype=[('x', ' ('npixcels', 'http://www.scipy.org/RecordArrays
but it looks like you have done the right thing and created a
RecordArray. What is wrong with this result?

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] list to numpy record array

2010-02-22 Thread Vincent Davis
I must be missing something simple. I have a list of lists data = "[['  0',
'  0', '234.0', '24.0', ' 25'], ['  1', '  0', '22428.0', '2378.1', '
25'],.." and what to make a record array from it but it gets screwed up
or I don't get it, maybe both. Notice that at this stage the items are
strings, not numbers, and there is whitespace not sure this matters.
Here is what is happening
adata = numpy.array(data,numpy.float64)

>>> adata
array([[  0.e+00,   0.e+00,   2.3400e+02,
  2.4000e+01,   2.5000e+01],
   ...,
   [  4.7700e+02,   4.7700e+02,   2.0700e+02,
  4.5800e+01,   2.5000e+01]])

This is what I would expect except it is not a record array.

This is not what I expect. I think I have tried every iteration including
using numpy dtaypes numpy.int32 or bdata = numpy.array(data, dtype = [('x',
int),('y', int),('mean',float),('stdv',float),('npixcels',int)])
What am I missing?

bdata = numpy.array(data, [('x', int),('y',
int),('mean',float),('stdv',float),('npixcels',int)])
>>> bdata
array([[(3153952, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0),
(206933603122, 0, 0.0, 0.0, 0), (808334386, 0, 0.0, 0.0, 0),
(3486240, 0, 0.0, 0.0, 0)],
   [(3219488, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0),
(1356161439282, 0, 0.0, 0.0, 0),
(54074581398322, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)],
   [(3285024, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0),
(206933931058, 0, 0.0, 0.0, 0), (925775666, 0, 0.0, 0.0, 0),
(3486240, 0, 0.0, 0.0, 0)],
   ...,
   [(3487540, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0),
(206933602866, 0, 0.0, 0.0, 0), (908996661, 0, 0.0, 0.0, 0),
(3486240, 0, 0.0, 0.0, 0)],
   [(3553076, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0),
(13561596370041137, 0, 0.0, 0.0, 0),
(62870573495603, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)],
   [(3618612, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0),
(206933798962, 0, 0.0, 0.0, 0), (942552372, 0, 0.0, 0.0, 0),
(3486240, 0, 0.0, 0.0, 0)]],

  dtype=[('x', 'http://vincentdavis.net> |
LinkedIn
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List append method: St Petersburg Game

2010-02-20 Thread AG

bob gailer wrote:

On 2/20/2010 7:43 AM, AG wrote:





Please let me know how I can clarify my question

1 - You are giving way too much information. We do not need to know 
the rules of the game or all the code. Our time to read email is 
limited. The less you tell us that is not relevant the better. 

Thanks Bob.

Also you don't show the code for the "next level of complexity". 


Here it is, then:

import random
import matplotlib.pyplot as plt
import math

def flipCoin():
   coinToss = random.randrange(1, 3)
   return coinToss

toss_list = []
tosscounts = []
winnings = []


for i in range(0, 10):

   while flipCoin() != 2:
   toss_list.append("Tails")
   flipCoin()


   print
   print "Heads"


   tosscounts.append( len(toss_list))

   if toss_list == 0:
   print "You won $2"
   winnings += 2

   else:
   toss_list.append( "Tail" )

   winnings += [2 ** len( toss_list )]
  


print
print tosscounts
print winnings

print "Here's the graph: "

for i in winnings:  # Convert int to float for log
   i * 1.0
  
plt.plot( [tosscounts], [winnings] )

plt.ylabel( "how often" )
plt.xlabel( "how much" )
plt.show()




The result of the first call to flipCoin is ignored.
Each cycle of the loop results in 2 calls to flipCoin. The result of 
the 2nd call is ignored.


Aha!  Thanks for spotting that.  Now fixed in the code cited above, but 
still gives the same problem.


Thanks for any further ideas.

AG

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List append method: St Petersburg Game

2010-02-20 Thread bob gailer

On 2/20/2010 7:43 AM, AG wrote:

Hi Pythonistas

I am having difficulty with applying the list.append(x) method to 
produce a list that will contain outputs which will become coordinates 
for a later call to Matplotlib.  Perhaps someone here can help me 
figure this out?



Please let me know how I can clarify my question

1 - You are giving way too much information. We do not need to know the 
rules of the game or all the code. Our time to read email is limited. 
The less you tell us that is not relevant the better. Also you don't 
show the code for the "next level of complexity". What you should show 
us is:

for i  in range( 0, 10 ):
some lists are initialized and appended to. What are they and how are 
they appended?


   #Main function:
   def flipCoin():
  coinToss = random.randrange(1, 3)
  return coinToss

   # Storage of output
   toss_list = []

   # Get things going
   flipCoin()

   # Want to capture the coin lands heads (2)
   while flipCoin() != 2:
  toss_list.append("Tails")
  flipCoin()


2 - The most obvious problem is here:

flipCoin()
while flipCoin() != 2:
   toss_list.append("Tails")
   flipCoin()

The result of the first call to flipCoin is ignored.
Each cycle of the loop results in 2 calls to flipCoin. The result of the 
2nd call is ignored.



The overall purpose of the game is, for this discussion, irrelevant, 
but some background info will be helpful I think.   The above program 
will give one run only and produces the output I expect. 


Then your expectation is misguided, given my comments regarding multiple 
calls to flipCoin! You don't actually know how many tosses were made!


[snip]

--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] List append method: St Petersburg Game

2010-02-20 Thread AG

Hi Pythonistas

I am having difficulty with applying the list.append(x) method to 
produce a list that will contain outputs which will become coordinates 
for a later call to Matplotlib.  Perhaps someone here can help me figure 
this out?


The basic program is below:

# St Petersburg Game: v. 2:
# Toss a coin.  If it is heads, win $2, if not keep
#   tossing it until it falls heads.
#   Heads first toss = H = $2
#   Heads third toss = TTH = $8
#   Heads fifth toss = H = $32

# The game is to win more by not scoring Heads

print """St Petersburg Game: win multiples of $2 the
more you land Tails"""

# Required libraries
import random
import matplotlib.pyplot as plt

#Main function:
def flipCoin():
   coinToss = random.randrange(1, 3)
   return coinToss

# Storage of output
toss_list = []

# Get things going
flipCoin()

# Want to capture the coin lands heads (2)
while flipCoin() != 2:
   toss_list.append("Tails")
   flipCoin()

# Heads lands & show output   
print

print "Heads"

print toss_list

# Interpret results & 'reward'
print "You flipped %d tails before landing Heads" % len(toss_list)

if toss_list == 0:
   print "You won $2"

else:
   toss_list.append( "Tail" )
   print "You won $%d" % 2 ** len(toss_list)



The overall purpose of the game is, for this discussion, irrelevant, but 
some background info will be helpful I think.   The above program will 
give one run only and produces the output I expect.  When I take this to 
the next level of complexity I run into problems.


1. I have tried to make this program run a given number of times, and 
use the for repetition loop to do this, basically:


for i  in range( 0, 10 ):

and then the above program is appropriately indented.

2. Collecting the number of coin "tosses" into a list appends these to a 
list just fine.  However, what this does is adds the numbers together so 
that one ends up like this:


[0, 1, 2, 4, 5, 6, 8, 10, 11, 15]

With a corresponding increase in the values derived from multiplying the 
exponent, thus:


[2, 4, 8, 32, 64, 128, 512, 2048, 4096, 65536]

Both are correct applications of the method, but I am unable to get the 
list to not sum the values up in the first list, these are not 
accumulative values, but discrete.  If I am understanding what is 
currently happening, the values are being accumulated, and I want to 
stop that from happening.


If this isn't clear, please let me know how I can clarify my question to 
help shape the relevance of the responses.


Thanks for any ideas.

AG
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor list as pair progamming plush toy

2010-02-13 Thread Steven D'Aprano
On Sat, 13 Feb 2010 02:33:04 am Mac Ryan wrote:

> whenever I get stuck, I begin to write a message to the
> list, and in the process of explaining what is the intended behaviour
> and outcome of my code, I systematically find the bug by myself.
[...]
> Does anybody else experience the same?

Yes!



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor list as pair progamming plush toy

2010-02-12 Thread Alan Gauld


"Mac Ryan"  wrote 


I know - this is slightly OT for the list - but I thought to share as
maybe this is a "hidden benefit" the list is bringing to a few people
without the tutors even knowing it.


Actually I think it is bang on topic.

One of the most common benefits of any online community 
is the way we are foced to think about propblems to write 
them down. Doing so ioften brings new solutions to mind.


In fact I often find solutioons to my own problems while 
replying to others! - even on seemingly unrelated issues :-)


And of course if the solution doesn't come you have the 
2nd level support option of actually posting and getting 
replies! :-) 


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor list as pair progamming plush toy

2010-02-12 Thread David Hutto


--- On Fri, 2/12/10, Hansen, Mike  wrote:

From: Hansen, Mike 
Subject: Re: [Tutor] Tutor list as pair progamming plush toy
To: tutor@python.org
Date: Friday, February 12, 2010, 11:55 AM

 

> -Original Message-
> From: tutor-bounces+mike.hansen=atmel@python.org 
> [mailto:tutor-bounces+mike.hansen=atmel@python.org] On 
> Behalf Of Mac Ryan
> Sent: Friday, February 12, 2010 8:33 AM
> To: tutor@python.org
> Subject: [Tutor] Tutor list as pair progamming plush toy
> 
> Have you ever got that piece of advice about - when you have 
> stuck on a
> bug you seem unable to track - getting a plush toy to whom you explain
> your code? (This is of course a workaround if you do not have a fellow
> developer to help you out).
> 
> Well... I found out this advice kind of works for me, with the notable
> difference that my plush toy is this mailing list. It works so
> wonderfully that indeed is several months I do not post any message:
> whenever I get stuck, I begin to write a message to the list, 
> and in the
> process of explaining what is the intended behaviour and outcome of my
> code, I systematically find the bug by myself.
> 
> I know - this is slightly OT for the list - but I thought to share as
> maybe this is a "hidden benefit" the list is bringing to a few people
> without the tutors even knowing it.
> 
> Does anybody else experience the same?
> 
> Cheers, :)
> Mac.
>
+1



  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


<    1   2   3   4   5   6   7   8   >